在vs上c++用函数实现json串,有没有能运行这个例子的代码


students: [
'{{repeat(100)}}',
{
no: '2021{{integer(100,999)}}',
name: '{{random("张三", "李四", "王五")}}',
age: '{{integer(18, 22)}}',
gender: '{{gender()}}',
email: '{{email()}}',
phone: '{{phone()}}',
address: '{{city()}}',
clazz: '2021级{{integer(10,10)}}班',
courses: [
{
name: '数学',
score: '{{floating(10, 100, 2)}}'
},
{
name: '英语',
score: '{{floating(10, 100, 2)}}'
},
{
name: 'C++',
score: '{{floating(10, 100, 2)}}'
}
],
friends: [
'{{repeat(3,5)}}',
{
id: '{{index()}}',
name: '{{firstName()}}*{{surname()}}',
parents:[
'{{repeat(2)}}',
{
}
]
}
]
}
]
}

能把报错发下嘛

https://github.com/yongssu/json
这里有个,参考下

https://github.com/上搜json就行,一搜一大把,nlohmann的就是C++实现的

函数呢,只看到数据,怎么看有没有问题……

C++用qt的库可以直接组装json的,很方便

可以采用JsonCpp这个工具进行操作。

给你一个实例参考:

[
    12, 
    12.34, 
    true, 
    "tom", 
    ["jack", "ace", "robin"], 
    {"sex":"man", "girlfriend":"lucy"}
]


#include <iostream>
#include <fstream> // IO 操作
#include <json/json.h>
using namespace std;
using namespace Json;


// 写 json文件
void writeJson()
{
    // 将最外层的数组看做一个Value
    // 最外层的Value对象创建
    Value root;
    // Value有一个参数为int 行的构造函数
    root.append(12);    // 参数进行隐式类型转换
    root.append(12.34);
    root.append(true);
    root.append("tom");
    
    // 创建并初始化一个子数组
    Value subArray;
    subArray.append("jack");
    subArray.append("ace");
    subArray.append("robin");
    root.append(subArray);
    
    // 创建并初始化子对象
    Value subObj;
    subObj["sex"] = "woman";  // 添加键值对
    subObj["girlfriend"] = "lucy";
    root.append(subObj);
    
    // 序列化
#if 1
    // 有格式的字符串
    string str = root.toStyledString();
#else
    FastWriter f;
    string str = f.write(root);
#endif
    // 将序列化的字符串写磁盘文件
    ofstream ofs("test.json");
    ofs << str;
    ofs.close();
}


// 读 json 文件  
void readJson()
{
    // 1. 将磁盘文件中的json字符串读到磁盘文件
    ifstream ifs("test.json");
    // 2. 反序列化 -> value对象
    Value root;
    Reader r;
    r.parse(ifs, root);
    // 3. 从value对象中将数据依次读出
    if (root.isArray())
    {
        // 数组, 遍历数组
        for (int i = 0; i < root.size(); ++i)
        {
            // 依次取出各个元素, 类型是value类型
            Value item = root[i];
            // 判断item中存储的数据的类型
            if (item.isString())
            {
                cout << item.asString() << ", ";
            }
            else if (item.isInt())
            {
                cout << item.asInt() << ", ";
            }
            else if (item.isBool())
            {
                cout << item.asBool() << ", ";
            }
            else if (item.isDouble())
            {
                cout << item.asFloat() << ", ";
            }
            else if (item.isArray())
            {
                for (int j = 0; j < item.size(); ++j)
                {
                    cout << item[j].asString() << ", ";
                }
            }
            else if (item.isObject())
            {
                // 对象
                // 得到所有的key
                Value::Members keys = item.getMemberNames();
                for (int k = 0; k < keys.size(); ++k)
                {
                    cout << keys.at(k) << ":" << item[keys[k]] << ", ";
                }
            }
            
        }
        cout << endl;
    }
}

    
int main()
{
    writeJson();
    readJson();
    return 0;
}




不是有cjson吗?直接调用不好吗?GIthub就有下载

用jsoncpp,我写过一篇博客:

cJson不是挺好的开源代码吗?可以直接用啊,自己写的容易有问题。

我感觉题主是需要 生成 json内容数据,现在给的是一个json数据模板,需要把其中{{firstName()}}类似的部分用真实的数据替代。

使用cjson可以实现你的需求

好像不是标准的json,里面有需要替换的标签。应该是需要程序先替换标签再做解析。

1、Value
Json::Value 是jsoncpp 中最基本、最重要的类,用于表示各种类型的对象,jsoncpp 支持的对象类型可见 Json::ValueType 枚举值。

可如下是用 Json::Value 类:
Json::Value json_temp; // 临时对象,供如下代码使用
json_temp["name"] = Json::Value("huchao");
json_temp["age"] = Json::Value(26);

Json::Value root; // 表示整个 json 对象
root["key_string"] = Json::Value("value_string"); // 新建一个 Key(名为:key_string),赋予字符串值:"value_string"。
root["key_number"] = Json::Value(12345); // 新建一个 Key(名为:key_number),赋予数值:12345。
root["key_boolean"] = Json::Value(false); // 新建一个 Key(名为:key_boolean),赋予bool值:false。
root["key_double"] = Json::Value(12.345); // 新建一个 Key(名为:key_double),赋予 double 值:12.345。
root["key_object"] = Json_temp; // 新建一个 Key(名为:key_object),赋予 json::Value 对象值。
root["key_array"].append("array_string"); // 新建一个 Key(名为:key_array),类型为数组,对第一个元素赋值为字符串:"array_string"。
root["key_array"].append(1234); // 为数组 key_array 赋值,对第二个元素赋值为:1234。
Json::ValueType type = root.type(); // 获得 root 的类型,此处为 objectValue 类型。

注:跟C++ 不同,JavaScript 数组可以为任意类型的值,所以 jsoncpp 也可以。
如上几个用法已经可以满足绝大部分 json 应用了,当然 jsoncpp 还有一些其他同能,比如说设置注释、比较 json 大小、交换 json 对象等,都很容易使用,大家自己尝试吧。

2、Writer
如上说了 Json::Value 的使用方式,现在到了该查看刚才赋值内容的时候了,查看 json 内容,使用 Writer 类即可。
Jsoncpp 的 Json::Writer 类是一个纯虚类,并不能直接使用。在此我们使用 Json::Writer 的子类:Json::FastWriter、Json::StyledWriter、Json::StyledStreamWriter。
顾名思义,用 Json::FastWriter 来处理 json 应该是最快的,下面我们来试试。
Json::FastWriter fast_writer;
std::cout << fast_writer.write(root) << std::endl;

输出结果为:
{"key_array":["array_string",1234],"key_boolean":false,"key_double":12.3450,"key_number":12345,"key_object":{"age":26,"name":"huchao"},"key_string":"value_string"}

再次顾名思义,用 Json::StyledWriter 是格式化后的 json,下面我们来看看 Json::StyledWriter 是怎样格式化的。
Json::StyledWriter styled_writer;
std::cout << styled_writer.write(root) << std::endl;
输出结果为:
{
"key_array" : [ "array_string", 1234 ],
"key_boolean" : false,
"key_double" : 12.3450,
"key_number" : 12345,
"key_object" : {
"age" : 26,
"name" : "huchao"
},
"key_string" : "value_string"
}

3、Reader
Json::Reader 是用于读取的,说的确切点,是用于将字符串转换为 Json::Value 对象的,下面我们来看个简单的例子。
Json::Reader reader;
Json::Value json_object;
const char* json_document = "{/"age/" : 26,/"name/" : /"huchao/"}";
if (!reader.parse(json_document, json_object))
return 0;

std::cout << json_object["name"] << std::endl;
std::cout << json_object["age"] << std::endl;

输出结果为:
"huchao"

你的json格式应该是这样的。

{
    "students":[
        {
            "no": "1001",
            "name": "张三",
            "age": "18",
            "gender": "gender",
            "email": "111@qq.com",
            "phone": "1234588....",
            "address": "江苏",
            "clazz": "2021级五班",
            "courses":[
                    {
                        "name": "数学",
                        "score": 20
                    },
                    {
                        "name":"英语",
                        "score":90
                    },
                    {
                        "name": "C++",
                        "score": 20
                    }
            ],
            "friends":[
                    {    "repeat":10,
                        "id":1002,
                        "name":"李四",
                        "parents":{
                            "father":"李三",
                            "monther":"李丽"
                        }
                    }
                ]
            
        }
    ]
}

实现代码,我是使用qt的qjsobdocument来进行实现的。

QJsonDocument readJson(QString path){
    QJsonDocument document;
    QFile file(path);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    if(!file.isOpen()){
        qDebug()<<path + "文件打开失败";
        return document;
    }
    QString value = file.readAll();
    file.close();
    QJsonParseError parseJsonErr;
    document = QJsonDocument::fromJson(value.toUtf8(),&parseJsonErr);
    if(parseJsonErr.error != QJsonParseError::NoError){
        qDebug()<<"json error:"<<parseJsonErr.error<<";error path:"<<path;
        return document;
    }
    return document;
}

int main()
{

    QJsonDocument document= readJson("D:/aaa.json");
    qDebug()<<"document = "<<document;
}

img