用C++实现的JSON解析器

用C++实现的JSON解析器

A simple C++11 json parser. 用C++11实现的json解析器。
源码地址(github):SimpleJSON

About

SimpleJSON is a lightweight json library written in C++.It surpports basic operations including reading and writting json documents.

SimpleJSON是一个轻量的由C++实现的json解析库。支持读写json文件等基本操作。

SimpleJSON mainly used for learning and communicating C++ programming and algorithm.It cannot ensure reliability in formal application yet.

SimpleJSON主要用来学习交流C++编程和算法。暂不能保证正式用途下的可靠性。

Dependencies

A C++11 compiler.

Usage

Add the C++ files in ./simple_jsonto your project like your other source files.

直接将 ./simple_json目录下的文件加入你的工程目录,按照自己的需求去编译即可。

Example

#include <iostream>
#include <string>
#include <fstream>
#include <json.hpp>

using namespace std;
using namespace sjson;

int main()
{
    ifstream ifs("/home/lpy/SimpleJSON/out1.json");    
    Json json(ifs);   		// construct json parser using input file stream
    if (json.succeed())         
    {
        string json_ptr;
        json.toString(json_ptr, true);   // get json string
        cout << json_ptr << endl;

        JsonNode& root = json.getRoot();  // get the root object
        int id = root["id"].as_int();  // get the integer value of item named "id" in root object
        cout << "id = " << id << endl;
        root["id"] = 567;  // set the value
        id = root["id"].as_int();
        cout << "id = " << id << endl;
        string layer = root["friend"]["layers"][1].as_string();  // get the  string value from array
        cout << layer << endl;

        root["friend"]["layers"][1] = "relu"; // set the value
        json.toString(json_ptr, true);
        cout << json_ptr << endl;

        root["friend"]["layers"].clear(); // clear array
        json.toString(json_ptr, true);
        cout << json_ptr << endl;

        root["author"] = "lpy"; // add an item named "author" and set the value
        json.toString(json_ptr, true);
        cout << json_ptr << endl;

        if (root["optimizers"].set_array(3)) // add an array named "optimizers" and size is 3
        {
            json.toString(json_ptr, true);
            cout << json_ptr << endl;
        }
        root["optimizers"][0] = "GradDescent";
        root["optimizers"][1] = "Momentumn";
        root["optimizers"][2] = "AdaGrad";
        json.toString(json_ptr, true);
        cout << json_ptr << endl;

        json.save("/home/lpy/SimpleJSON/out2.json", true); // save as json file
    }            
    

	return 0;
}

The code above just shows part of operations.See the source code to learn more!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值