C++中JSON文件的读取

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、C#Java、JavaScript、PerlPython等)。这些特性使JSON成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)。


从文件中读取JSON

JSON 示例

{
  "face": [
    {
      "attribute": {
        "age": {
          "range": 5,
          "value": 35
        },
        "gender": {
          "confidence": 99.9995,
          "value": "Male"
        },
        "glass": {
          "confidence": 98.8995,
          "value": "None"
        },
        "pose": {
          "pitch_angle": {
            "value": -0.000006
          },
          "roll_angle": {
            "value": 5.32508
          },
          "yaw_angle": {
            "value": -22.432627
          }
        },
        "race": {
          "confidence": 98.62100000000001,
          "value": "Asian"
        },
        "smiling": {
          "value": 97.3715
        }
      },
      "face_id": "2f60c56506b691c0384e2694fed1c819",
      "position": {
        "center": {
          "x": 51.463415,
          "y": 25.121951
        },
        "eye_left": {
          "x": 46.197561,
          "y": 20.161
        },
        "eye_right": {
          "x": 56.724146,
          "y": 21.142171
        },
        "height": 22.926829,
        "mouth_left": {
          "x": 45.610732,
          "y": 30.399024
        },
        "mouth_right": {
          "x": 56.01561,
          "y": 31.734146
        },
        "nose": {
          "x": 49.063659,
          "y": 27.171951
        },
        "width": 22.926829
      },
      "tag": ""
    }
  ],
  "img_height": 410,
  "img_id": "84c20011223acd4efa0b5aa13fc2146d",
  "img_width": 410,
  "session_id": "42c5db376fdc4da9855d0135b5e414e2",
  "url": "http://www.faceplusplus.com.cn/wp-content/themes/faceplusplus/assets/img/demo/16.jpg?v=2"
}

JSON 数据整体输出

#include
#include
#include
#include "json.h"

using namespace std;

void main()
{


	Json::Reader reader;
	Json::Value root;

	ifstream is;   //从文件中读取
	is.open("face.json", ios::binary);

	assert(reader.parse(is, root));

	Json::StyledWriter sw;     //缩进输出
	cout << "缩进输出" << endl;
	cout << sw.write(root) << endl << endl;
	
}

C++中JSON文件的读取_第1张图片
JSON 数据单独提取

cout << root["img_height"].asInt() << endl;

	int i = root["face"].size();
	cout << root["face"][i-1]["attribute"]["age"]["range"].asInt() << endl;

	cout << root["face"][i-1]["face_id"].asString() << endl;




参考文献

【1】http://my.oschina.net/Tsybius2014/blog/289527

你可能感兴趣的:(C/C++)