There are more elegant ways to write to files
tiantianaixuexi opened this issue · 2 comments
tiantianaixuexi commented
Hello, I want to write an object to a Json array in an existing file
like this:
{
"UserData": []
}
I've implemented it so far, writing data to this Json array
{
"UserData": [
{
"name": "dasdsad",
"email": "dasdsa",
"phone": "asdasdas",
"LiuYan": "asdasdsa"
},
{
"name": "dasdsad",
"email": "dasdsa",
"phone": "asdasdas",
"LiuYan": "asdasdsa"
},
{
"name": "dasdsad",
"email": "dasdsa",
"phone": "asdasdas",
"LiuYan": "asdasdsa"
}
]
}
this is code :
yyjson_doc* doc = yyjson_read(req->body.c_str(), req->body.length(), 0);
yyjson_val* root = yyjson_doc_get_root(doc);
yyjson_val* nameVal = yyjson_obj_get(root, "name");
yyjson_val* emailVal = yyjson_obj_get(root, "email");
yyjson_val* phoneVal = yyjson_obj_get(root, "phone");
yyjson_val* liuyanVal = yyjson_obj_get(root, "liuyan");
if (root != nullptr) [[likely]]
{
yyjson_doc* readDoc = yyjson_read_file("./ZhongYao/User.json", 0, NULL, NULL);
yyjson_mut_doc* ReadMutdoc = yyjson_doc_mut_copy(readDoc, NULL);
yyjson_mut_val* ReadMutRoot = yyjson_mut_doc_get_root(ReadMutdoc);
yyjson_mut_val* UserData = yyjson_mut_obj_get(ReadMutRoot, "UserData");
yyjson_mut_val* UserJsonVal = yyjson_mut_obj(ReadMutdoc);
yyjson_mut_obj_add_str(ReadMutdoc, UserJsonVal,"name",yyjson_get_str(nameVal));
yyjson_mut_obj_add_str(ReadMutdoc, UserJsonVal, "email", yyjson_get_str(emailVal));
yyjson_mut_obj_add_str(ReadMutdoc, UserJsonVal, "phone", yyjson_get_str(phoneVal));
yyjson_mut_obj_add_str(ReadMutdoc, UserJsonVal, "LiuYan", yyjson_get_str(liuyanVal));
yyjson_mut_arr_append(UserData, UserJsonVal);
yyjson_write_flag flg = YYJSON_WRITE_PRETTY | YYJSON_WRITE_ESCAPE_UNICODE;
yyjson_write_err err;
yyjson_mut_write_file("./ZhongYao/User.json", ReadMutdoc, flg,NULL,&err);
if (err.code)
{
yyjson_doc_free(doc);
yyjson_doc_free(readDoc);
yyjson_mut_doc_free(ReadMutdoc);
fmt::print("write error {}: {}\n", err.code, err.msg);
}
}
Yes, it works perfectly, but it's a lot of code. Is there a simple way to write code to make it simpler?
ibireme commented
This is a C library, so it may look like there are a lot of codes. If you prefer C++, you can write some simple wrapping yourself, or use a third-party wrapped C++ library, such as cpp-yyjson.
tiantianaixuexi commented
OK,Theank you