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

#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

## 模板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调试运行


C语言中有多种方法可以进行JSON解析。一种常用的方法是使用开源RapidJSON。RapidJSON是一个只有头文件的C,使用起来非常方便。你只需要下载并解压后,将include/rapidjson目录拷贝到你的项目中即可开始使用。RapidJSON支持SAX和DOM两种解析方式,SAX解析器将JSON解析为事件序列,而DOM解析器将JSON解析为内存中的树形结构。 另外还有一个流行的CJsonCpp,也是用于JSON解析和生成的开源JsonCpp与RapidJSON具有很多相似的功能,但也有一些不同之处。你可以根据自己的需求选择使用其中的一个来进行C语言中的JSON解析。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [json.zip_JSON_c/c++ json_c/c++ json 解析_json解析 c++_解析json](https://download.csdn.net/download/weixin_42662605/86531966)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [【C/C++C++Json解析和生成的开源:RapidJsonJsonCpp](https://blog.csdn.net/weixin_43729127/article/details/129473932)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值