JSON: JavaScript Object Notation(JavaScript 对象表示法),是存储和交换文本信息的语法。它类似 XML,但比 XML 更小、更快,更易解析。
JSON 是轻量级的文本数据交换格式,独立于语言,具有自我描述性,更易理解。
JSON 文本格式在语法上与创建 JavaScript 对象的代码相同,由于这种相似性,无需解析器,JavaScript 程序能够使用内建的 eval() 函数,用 JSON 数据来生成原生的 JavaScript 对象。
例如:
var sites = [
{ "name":"foo" , "url":"www.foo.com" },
{ "name":"google" , "url":"www.google.com" },
{ "name":"微博" , "url":"www.weibo.com" }
];
c++中有多种方法可以解析json数据,包括Jsoncpp和Boost库的property_tree。
Jsoncpp是个跨平台的开源库,使用的比较多。
下载、编译、安装请参考相关文档。
% cat test.json
[{"name":"姓名", "age":27}]
#include
#include
#include
#include
#include
#include
using namespace std;
int main(void)
{
ifstream ifs;
ifs.open("test.json");
assert(ifs.is_open());
Json::Reader reader;
Json::Value root;
if (!reader.parse(ifs, root, false))
{
cout << "reader parse error: " << strerror(errno) << endl;
return -1;
}
string name;
int age;
int size;
size = root.size();
cout << "total " << size << " elements" << endl;
for (int i = 0; i < size; ++i)
{
name = root[i]["name"].asString();
age = root[i]["age"].asInt();
cout << "name: " << name << ", age: " << age << endl;
}
return 0;
}
% ./json_test
total 1 elements
name: 姓名, age: 27
string name = root["name"].asString();
int age = root["age"].asInt();
cout << "name: " << name << ", age: " << age << endl;
%cat test1.json
{
"beijing": {
"gdp": 20,
"population": 200
},
"shanghai": {
"gdp": 20,
"population": 200
}
}
int bj_gdp = root["beijing"]["gdp"].asInt();
int bj_population = root["beijing"]["population"].asInt();
int sh_gdp = root["shanghai"]["gdp"].asInt();
int sh_population = root["shanghai"]["population"].asInt();
static void write_json(string f)
{
Json::Value root;
Json::FastWriter writer;
Json::Value person;
person["age"] = 28;
person["name"] = "sb";
root.append(person);
string json_file = writer.write(root);
ofstream ofs;
ofs.open(f);
assert(ofs.is_open());
ofs << json_file;
return;
}
% cat test_write.json
[{"age":28,"name":"sb"}]