JSONの文字列をパースするのをいろんな言語で書いてみた

まとめリンク: 同じことをいろんな言語で書いてみたシリーズ



C++

#include <iostream>
// https://github.com/nlohmann/json.git をcloneして
// single_include/nlohmann/json.hppをソースと同じところに置いておく
#include "json.hpp"
int main(int argc, char* argv[]){
    std::string json_text = \
u8R"##({
  "mysql" : {
    "host" : "192.168.0.3",
    "port" : 3306,
    "user" : "hoge",
    "password" : "fuga",
    "database" : "hige",
    "table" : "hage"
  }
})##";
    auto json_data = nlohmann::json::parse(json_text);
    std::cout << json_data["mysql"]["host"] << std::endl;
}


Ruby

#!/usr/local/bin/ruby -Ku
require 'json'
json_text = <<'EOJSON'
{
  "mysql" : {
    "host" : "192.168.0.3",
    "port" : 3306,
    "user" : "hoge",
    "password" : "fuga",
    "database" : "hige",
    "table" : "hage"
  }
}
EOJSON
json_data = JSON.parse(json_text)
puts(json_data['mysql']['host'])


Crystal

require "json"
json_text = <<-EOJSON
  {
    "mysql" : {
      "host" : "192.168.0.3",
      "port" : 3306,
      "user" : "hoge",
      "password" : "fuga",
      "database" : "hige",
      "table" : "hage"
    }
  }
  EOJSON
json_data = JSON.parse(json_text)
puts(json_data["mysql"]["host"])


Rust

use serde::{Deserialize};  // https://github.com/serde-rs/json
#[derive(Deserialize, Debug)]
struct MysqlConfig {
  host: String,
  port: u16,
  user: String,
  password: String,
  database: String,
  table: String
}
#[derive(Deserialize, Debug)]
struct MysqlData {
  mysql: MysqlConfig
}
fn main() {
  let json_text =
r#"{
  "mysql" : {
    "host" : "192.168.0.3",
    "port" : 3306,
    "user" : "hoge",
    "password" : "fuga",
    "database" : "hige",
    "table" : "hage"
  }
}"#;
  let json_data: MysqlData = serde_json::from_str(&json_text).unwrap();
  println!("{}", json_data.mysql.host);
}


Python3

#!/usr/bin/python3
import json
json_text = """{
  "mysql" : {
    "host" : "192.168.0.3",
    "port" : 3306,
    "user" : "hoge",
    "password" : "fuga",
    "database" : "hige",
    "table" : "hage"
  }
}"""
json_data = json.loads(json_text)
print(json_data['mysql']['host'])


Node.js

#!/usr/local/bin/node
"use strict";
const json_text = `{
  "mysql" : {
    "host" : "192.168.0.3",
    "port" : 3306,
    "user" : "hoge",
    "password" : "fuga",
    "database" : "hige",
    "table" : "hage"
  }
}`;
const json_data = JSON.parse(json_text);
console.log(json_data['mysql']['host']);


C#

using System;
using System.Text.Json;
namespace json_test
{
  class Program
  {
    static void Main(string[] args)
    {
      string json_text =
@"{
  ""mysql"" : {
    ""host"" : ""192.168.0.3"",
    ""port"" : 3306,
    ""user"" : ""hoge"",
    ""password"" : ""fuga"",
    ""database"" : ""hige"",
    ""table"" : ""hage""
  }
}";
      JsonDocument json_data = JsonDocument.Parse(json_text);
      Console.WriteLine(
        json_data.RootElement.GetProperty("mysql").GetProperty("host").GetString()
      );
    }
  }
}