「C++の応用 - JSON」の版間の差分

提供:MochiuWiki : SUSE, EC, PCB
ナビゲーションに移動 検索に移動
 
(同じ利用者による、間の8版が非表示)
36行目: 36行目:
*: <code>std::vector</code>クラスや<code>std::map</code>クラスの使用方法を知っていれば、すぐに使用することができる。
*: <code>std::vector</code>クラスや<code>std::map</code>クラスの使用方法を知っていれば、すぐに使用することができる。
<br>
<br>
<u>JSON for Modern C++は、MITライセンスである。</u><br>
<u>JSON for Modern C++は、[[その他_-_ソフトウェアライセンス#MIT_License|MITライセンス]]である。</u><br>
<br>
<br>
==== JSON for Modern C++のインストール ====
==== JSON for Modern C++のインストール ====
60行目: 60行目:
ダウンロードしたファイルを解凍する。<br>
ダウンロードしたファイルを解凍する。<br>
各プロジェクトファイルに配置して、json.hppをインクルードして使用する。<br>
各プロジェクトファイルに配置して、json.hppをインクルードして使用する。<br>
<br>
==== JSONファイルの読み込み ====
<syntaxhighlight lang="c++">
#include <iostream>
#include <fstream>
#include "nlohmann/json.hpp"
using namaspace std;
// JSONファイルの読み込み
string filename = "JSON-Sample.json";
ifstream ifs(filename.c_str());
if (ifs.good()) {
    json m_json;
    ifs >> m_json
    // 読み込んだデータを各変数へ代入
    string firstname = m_json["FirstName"];
    string lastname  = m_json["LastName"];
    int    age      = m_json["Age"];
    double height    = m_json["Height"];
    // 各データの表示
    cout << "firstname:" << firstname << endl;
    cout << "lastname:"  << lastname << endl;
    cout << "age:"      << age << endl;
    cout << "height:"    << height << endl;
}
else {
    // JSONファイルの読み込みに失敗した場合
    cout << "ファイルの読み込みに失敗しました" << endl;
}
</syntaxhighlight>
<br>
<br>


==== 使用方法 ====
==== JSONファイルの書き込み ====
  <syntaxhighlight lang="c++">
  <syntaxhighlight lang="c++">
  #include <iostream>
  #include <iostream>
  #include <fstream>
  #include <fstream>
  #include "nlohmann/json.hpp"
  #include "nlohmann/json.hpp"
using namaspace std;
// 書き込むJSONファイルの内容
json m_json = {
    {"FirstName", "Jung kook"},
    {"LastName",  "Park"},
    {"Country",  "Korea"},
    {"Age",      25},
    {"Height"    180.5f}
};
// JSONファイルのパス
string filename  = "JSON-Sample.json";
// JSONファイルへ書き込み
ofstream writing_file;
writing_file.open(filename, ios::out);  // JSONファイルの作成またはオープン
writing_file << m_json.dump() << endl;  // JSON型のオブジェクトを書き込むには、シリアライズを行う必要がある
writing_file.close();                  // JSONファイルを閉じる
</syntaxhighlight>
<br>
==== JSONファイルの編集 ====
以下の例では、"Age"キーの値を30に変更、"Height"キーと値を削除している。<br>
<br>
<syntaxhighlight lang="json">
# 編集前のJSONデータ (JSON-Sample.jsonファイル)
   
   
int main()
  {
  {
     // JSONファイルの内容
     "FirstName": "Jung kook",
    json m_json = {
    "LastName": "Park",
                  {"FirstName", "Jung kook"},
    "Country":   "Korea",
                  {"LastName", "Park"},
    "Age":       25,
                  {"Country",   "Korea"},
    "Height":    180.5
                  {"Age",       25},
}
                  {"Height"     180.5f}
</syntaxhighlight>
                  };
<br>
<syntaxhighlight lang="c++">
#include <iostream>
#include <fstream>
#include "nlohmann/json.hpp"
using namaspace std;
using json = nlohmann::json;
   
   
    // JSONファイルの名前
// JSONファイルの読み込み
    string filename = "JSON-Sample";
string filename = "JSON-Sample.json";
    string Extension = ".json";
ifstream ifs(filename.c_str());
    filename += Extension;
   
   
    // JSONファイルへ書き込み
if (ifs.good()) {
    ofstream writing_file;
     json m_json;
    writing_file.open(filename, ios::out);  // JSONファイルの作成またはオープン
     ifs >> m_json;
     writing_file << m_json.dump() << endl; // JSON型のオブジェクトを書き込むには、シリアライズを行う必要がある
     writing_file.close();                   // JSONファイルを閉じる
   
   
     // JSONファイルの読み込み
     // ファイルを閉じる
     string filename = "JSON-Sample.json";
     ifs.close();
    ifstream ifs(filename.c_str());
    if (ifs.good())
    {
      json m_json;
      ifs >> m_json
   
   
      // 読み込んだデータを各変数へ代入
    // Ageを30に変更
      string firstname = m_json["FirstName"];
    m_json["Age"] = 30;
      string lastname  = m_json["LastName"];
      int    age      = m_json["Age"];
      double height    = m_json["Height"];
   
   
      // 各データの表示
    // Heightを削除
      cout << "firstname:" << firstname << endl;
     m_json.erase("Height");
      cout << "lastname:" << lastname << endl;
      cout << "age:" << age << endl;
      cout << "height:" << height << endl;
     }
    else
    {  // JSONファイルの読み込みに失敗した場合
      cout << "ファイルの読み込みに失敗しました" << endl;
    }
   
   
     return 0;
     // 変更したJSONをファイルに書き込み
    ofstream writing_file;
    writing_file.open(filename, ios::out);
    writing_file << m_json.dump() << endl;
    writing_file.close();
}
else {
    // JSONファイルの読み込みに失敗した場合
    cout << "ファイルの読み込みに失敗しました" << endl;
  }
  }
  </syntaxhighlight>
  </syntaxhighlight>
<br><br>
<br><br>


{{#seo:
|title={{PAGENAME}} : Exploring Electronics and SUSE Linux | MochiuWiki
|keywords=MochiuWiki,Mochiu,Wiki,Mochiu Wiki,Electric Circuit,Electric,pcb,Mathematics,AVR,TI,STMicro,AVR,ATmega,MSP430,STM,Arduino,Xilinx,FPGA,Verilog,HDL,PinePhone,Pine Phone,Raspberry,Raspberry Pi,C,C++,C#,Qt,Qml,MFC,Shell,Bash,Zsh,Fish,SUSE,SLE,Suse Enterprise,Suse Linux,openSUSE,open SUSE,Leap,Linux,uCLnux,Podman,電気回路,電子回路,基板,プリント基板
|description={{PAGENAME}} - 電子回路とSUSE Linuxに関する情報 | This page is {{PAGENAME}} in our wiki about electronic circuits and SUSE Linux
|image=/resources/assets/MochiuLogo_Single_Blue.png
}}


__FORCETOC__
__FORCETOC__
[[カテゴリ:C++]]
[[カテゴリ:C++]]

2025年1月9日 (木) 00:20時点における最新版

概要



JSON for Modern C++

JSON for Modern C++の概要

世の中には無数のJSONライブラリがあり、それぞれに存在理由がある。
JSON for Modern C++では、次のような設計目標がある。

  • 直感的な構文
    Python等のプログラム言語では、JSONはファーストクラスのデータ型のように見える。
    C++の演算子の全て使用して、コード内で同じ感覚を実現している。

  • 統合の簡素化
    ソースコード全体は、単一のヘッダファイルであるjson.hppファイルで構成されているのみである。
    ライブラリ、サブプロジェクト、依存関係、複雑なビルドシステムは不要である。
    JSON for Modern C++は、C++ 11で記述されており、コンパイラフラグやプロジェクト設定を調整する必要は無い。

  • 高い品質
    JSON for Modern C++は十分にテストされており、全ての例外的な動作を含むソースコードを100%カバーしている。
    また、ValgrindとClang Sanitizersでメモリリークが無いことを確認している。
    さらに、Google OSS-Fuzzは、全てのパーサーに対してファズテストを24時間年中無休で実行し、これまでに数十億のテストを効果的に実行している。
    高品質を維持するために、プロジェクトはコアインフラストラクチャイニシアチブ (CII)のベストプラクティスに従っている。

  • メモリ効率
    各JSON オブジェクトには、1つのポインタ (共用体の最大サイズ)と1つの列挙要素 (1バイト)のオーバーヘッドがある。
    デフォルトの汎化では、次のC++データ型が使用される。
    文字列の場合はstd::string
    数値の場合はint64_t、uint64_t、double
    オブジェクトの場合はstd::map
    配列の場合はstd::vector
    ブール値の場合はbool
    また、必要に応じて汎用クラスのBasic_jsonをテンプレート化することができる。

  • 開発効率
    より高速なJSONライブラリは存在するが、単一ヘッダファイルでJSONサポートを追加することにより、開発を高速化することができる。
    std::vectorクラスやstd::mapクラスの使用方法を知っていれば、すぐに使用することができる。


JSON for Modern C++は、MITライセンスである。

JSON for Modern C++のインストール

Linux

JSON for Modern C++のGithubにアクセスして、ソースコードをダウンロードする。
ダウンロードするファイルは、Source code (tar.gz)と記載されているリンクである。

ダウンロードしたファイルを解凍する。

tar xf json-<バージョン>.tar.xz
cd json-<バージョン>


JSON for Modern C++をビルドおよびインストールする。

mkdir build && cd build

cmake -DCMAKE_INSTALL_PREFIX=<JSON for Modern C++のインストールディレクトリ> ..
make -j $(nproc)
make install


Windows

JSON for Modern C++のGithubにアクセスして、ソースコードをダウンロードする。
ダウンロードするファイルは、include.zipまたはjson.hppと記載されているリンクである。

ダウンロードしたファイルを解凍する。
各プロジェクトファイルに配置して、json.hppをインクルードして使用する。

JSONファイルの読み込み

 #include <iostream>
 #include <fstream>
 #include "nlohmann/json.hpp"
 
 using namaspace std;
 
 // JSONファイルの読み込み
 string filename = "JSON-Sample.json";
 ifstream ifs(filename.c_str());
 
 if (ifs.good()) {
    json m_json;
    ifs >> m_json
 
    // 読み込んだデータを各変数へ代入
    string firstname = m_json["FirstName"];
    string lastname  = m_json["LastName"];
    int    age       = m_json["Age"];
    double height    = m_json["Height"];
 
    // 各データの表示
    cout << "firstname:" << firstname << endl;
    cout << "lastname:"  << lastname << endl;
    cout << "age:"       << age << endl;
    cout << "height:"    << height << endl;
 }
 else {
    // JSONファイルの読み込みに失敗した場合
    cout << "ファイルの読み込みに失敗しました" << endl;
 }


JSONファイルの書き込み

 #include <iostream>
 #include <fstream>
 #include "nlohmann/json.hpp"

 using namaspace std;
 
 // 書き込むJSONファイルの内容
 json m_json = {
    {"FirstName", "Jung kook"},
    {"LastName",  "Park"},
    {"Country",   "Korea"},
    {"Age",       25},
    {"Height"     180.5f}
 };
 
 // JSONファイルのパス
 string filename  = "JSON-Sample.json";
 
 // JSONファイルへ書き込み
 ofstream writing_file;
 writing_file.open(filename, ios::out);  // JSONファイルの作成またはオープン
 writing_file << m_json.dump() << endl;  // JSON型のオブジェクトを書き込むには、シリアライズを行う必要がある
 writing_file.close();                   // JSONファイルを閉じる


JSONファイルの編集

以下の例では、"Age"キーの値を30に変更、"Height"キーと値を削除している。

 # 編集前のJSONデータ (JSON-Sample.jsonファイル)
 
 {
    "FirstName": "Jung kook",
    "LastName":  "Park",
    "Country":   "Korea",
    "Age":       25,
    "Height":    180.5
 }


 #include <iostream>
 #include <fstream>
 #include "nlohmann/json.hpp"
 
 using namaspace std;
 
 using json = nlohmann::json;
 
 // JSONファイルの読み込み
 string filename = "JSON-Sample.json";
 ifstream ifs(filename.c_str());
 
 if (ifs.good()) {
    json m_json;
    ifs >> m_json;
 
    // ファイルを閉じる
    ifs.close();
 
    // Ageを30に変更
    m_json["Age"] = 30;
 
    // Heightを削除
    m_json.erase("Height");
 
    // 変更したJSONをファイルに書き込み
    ofstream writing_file;
    writing_file.open(filename, ios::out);
    writing_file << m_json.dump() << endl;
    writing_file.close();
 }
 else {
    // JSONファイルの読み込みに失敗した場合
    cout << "ファイルの読み込みに失敗しました" << endl;
 }