04_c/c++开源库 json解析jsoncpp库

1.说明与安装

说明:

c++ json字符解析

安装:

sudo apt-get install libjsoncpp-dev

编译依赖

pkg-config --cflags --libs jsoncpp

-I/usr/include/jsoncpp -ljsoncpp

编译选项: -I/usr/include/jsoncpp

连接选项: -ljsoncpp


2.实例

1.代码

1_jsonCpp_解析字符串_增.删.改.查.保存.cc

c++ 复制代码
#include <iostream>
#include <fstream>
#include <memory>
#include <json/json.h>

// 假设我们有一个JSON字符串或文件内容
std::string json_data = R"({
    "name": "John Doe",
    "age": 30,
    "city": "New York",
    "hobbies": ["reading", "gaming"]
})";

void parse_and_modify_json()
{
    // 1.解析JSON字符串
    Json::Value root;
    Json::CharReaderBuilder builder;
    std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
    JSONCPP_STRING err;
    bool parsingSuccessful = reader->parse(json_data.c_str(), json_data.c_str() + json_data.size(), &root, &err);
    if (!parsingSuccessful)
    {
        std::cout << "Failed to parse JSON: " << std::endl;
        return;
    }

    // 2.改: 修改JSON数据
    root["name"] = "Jane Doe";          // 修改名字
    root["age"] = 31;                   // 修改年龄
    root["hobbies"][0] = "programming"; // 替换第一个爱好
    // 添加新的键值对
    root["job"] = "Software Engineer";

    // 3.查
    std::string name = root["name"].asString();
    int age = root["age"].asInt();
    std::cout << "Name: " << name << std::endl;
    std::cout << "Age: " << age << std::endl;

    // 4.转为string
    bool shouldUseOldWay = false;   //使用旧版本的API
    if (shouldUseOldWay)
    {
        Json::FastWriter writer;
        const std::string json_file = writer.write(root);
        std::cout <<"old way ---\n"<< json_file << std::endl;
    }
    else
    {
        Json::StreamWriterBuilder builder;
        const std::string json_file = Json::writeString(builder, root);
        std::cout <<"new way ---\n"<< json_file << std::endl;
    }

    // 5.写入文件
    std::ofstream outfile("output.json");
    if (outfile.is_open())
    {
        Json::StreamWriterBuilder builder;
        builder["commentStyle"] = "None";
        builder["indentation"] = "   "; // 增加缩进
        std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
        writer->write(root, &outfile);
    }
    outfile.close();
}

int main(void)
{
    parse_and_modify_json();
    return 0;
}

2.scons构建

SConstruct

python 复制代码
## 模板1
import os
env = Environment()

env["PROGSUFFIX"] = ".out"            # 可执行后缀.out
env["CCFLAGS"] = " -g3 -O0 -Wall"  # gdb 调试开关

env.MergeFlags(
    [
        "!pkg-config --cflags --libs jsoncpp",
    ]
)
src_list = [
    "1_jsonCpp_解析字符串_增.删.改.查.保存.cc",
]
for src in src_list:
    env.Program(Split(src))

scons

scons: Reading SConscript files ...

scons: done reading SConscript files.

scons: Building targets ...

g++ -o 1_jsonCpp_解析字符串_增.删.改.查.保存.o -c -g3 -O0 -Wall -I/usr/include/jsoncpp 1_jsonCpp_解析字符串_增.删.改.查.保存.cc

g++ -o 1_jsonCpp_解析字符串_增.删.改.查.保存.out 1_jsonCpp_解析字符串_增.删.改.查.保存.o -ljsoncpp

scons: done building targets.

3.运行

./1_jsonCpp_解析字符串_增.删.改.查.保存.out

Name: Jane Doe

Age: 31

new way ---

{

"age" : 31,

"city" : "New York",

"hobbies" :

[

"programming",

"gaming"

],

"job" : "Software Engineer",

"name" : "Jane Doe"

}

建议使用gdb调试运行,查看代码流程.

3.其它实例

jsoncpp 在线代码

2_jsonCpp_从文件读取.cc

可以git clone https://gitee.com/zero2200/3_cpp-practice.git,

vscode 打开代码, F5 gdb调试运行


相关推荐
Ljw...16 分钟前
DeepSeek+Kimi生成高质量PPT
数据库·c++·powerpoint·ppt·deepseek
敲上瘾16 分钟前
基础dp——动态规划
java·数据结构·c++·python·算法·线性回归·动态规划
禁默1 小时前
C++之旅-C++11的深度剖析(1)
开发语言·c++
张有志_1 小时前
STL容器终极解剖:C++ vector源码级实现指南 | 从内存分配到异常安全的全流程避坑
c语言·c++·算法·开源·visual studio
挨代码1 小时前
UE_C++ —— Delegates
c++·ue
美股研究社2 小时前
百度智能云AI收入增3倍,2025开源引流打赢生态战
人工智能·百度·开源
web_155342746562 小时前
性能巅峰对决:Rust vs C++ —— 速度、安全与权衡的艺术
c++·算法·rust
9毫米的幻想3 小时前
【Linux系统】—— 冯诺依曼体系结构与操作系统初理解
linux·运维·服务器·c语言·c++
星霜旅人3 小时前
开源机器学习框架
人工智能·机器学习·开源
Mr.Wang8093 小时前
条款23:宁以non-member、non-friend替换member函数
开发语言·c++