ibireme / yyjson

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

write array obj not correctly #169

Closed ldyoungGod closed 3 months ago

ldyoungGod commented 3 months ago

//code

include

include

include

include "yyjson.h"

int main(int argc, char argv[]) { yyjson_mut_doc doc = yyjson_mut_doc_new(NULL); yyjson_mut_val* root = yyjson_mut_obj(doc); yyjson_mut_doc_set_root(doc,root);

yyjson_mut_val* array = yyjson_mut_arr(doc);
yyjson_mut_obj_add_val(doc,root,"vecObj",array);
for(int i = 0; i < 3; ++i)
{
    char szName[64] = {0};
    sprintf(szName,"obj%d",i+1);
    yyjson_mut_val* obj1 = yyjson_mut_arr_add_obj(doc,array);
    yyjson_mut_obj_add_str(doc,obj1,"name",szName);
}

const char* json = yyjson_mut_write(doc,0,NULL);
if(json)
{
    yyjson_mut_write_file("./myjson.json",doc,YYJSON_WRITE_PRETTY,NULL,NULL);
    free((void*)json);
}
yyjson_mut_doc_free(doc);
return 0;

}

//real output { "vecObj": [ { "name": "obj3" }, { "name": "obj3" }, { "name": "obj3" } ] }

//should output { "vecObj": [ { "name": "obj1" }, { "name": "obj2" }, { "name": "obj3" } ] }

ibireme commented 3 months ago

The szName was modified after being added to the document, so the string should be copied using yyjson_mut_obj_add_strcpy(). See: https://github.com/ibireme/yyjson/blob/master/doc/API.md#api-for-string

ldyoungGod commented 3 months ago

这是来自QQ邮箱的假期自动回复邮件。   您好,我最近正在休假中,无法亲自回复您的邮件。我将在假期结束后,尽快给您回复。