ibireme / yyjson

The fastest JSON library in C
https://ibireme.github.io/yyjson/doc/doxygen/html/
MIT License
3.04k stars 262 forks source link

There are more elegant ways to write to files #118

Closed tiantianaixuexi closed 1 year ago

tiantianaixuexi commented 1 year ago

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 1 year ago

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 1 year ago

OK,Theank you