简体   繁体   中英

How do I save an array of JSON encoded contents with the square bracket?

I'm using Javascript and NodeJS to dynamically create an array of JSON objects. I want to save this array of JSON objects to a .json file for future use. However, when I save the file, I only get the contents separated by commas, but not the outer square brackets.

I use the fs.writeFile to do this. I have the dynamically created array with JSON objects, separated by commas. My function is shown below.

fs.writeFile('json_files/output_'+id+'.json', ret_vals, function (err) {
                    if (err) 
                        return console.log(err);
                    console.log('Success!');
                });

The file I get from the output looks like this:

{"x":"y"}, {"x":"z"}, {"x":"t"}

However, I want my .json file to look like this: [{"x":"y"}, {"x":"z"}, {"x":"t"} ]

So basically, I want the array brackets to exist too. For reference, I create an array called ret_vals using let ret_vals = [], and then use .push() to add these jsons to it.

If I use stringify, I get the brackets, but the array contents are also surrounded by quotation marks, making it impossible to run any JSON comparator on the contents, since it just identifies that the whole sentence is different. How would I proceed to do what I want?

是的json.stringify将适用于您的问题,当您需要对其进行处理时,请使用json parse将字符串化的对象转换为数组对象

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM