简体   繁体   中英

NodeJs JSON parsing issue

I have a .json file where i have people's names stored. I'm reading the content from this file using the file system from Node Manager and then I'm trying to convert this json to string and parsing it to JS object. After parsing it to JS object i get as type string instead of object. Here is the example json file :

{
"21154535154122752": {
    "username": "Stanislav",
    "discriminator": "0001",
    "id": "21154535154122752",
    "avatar": "043bc3d9f7c2655ea2e3bf029b19fa5f",
    "shared_servers": [
        "Reactiflux",
        "Discord Testers",
        "Official Fortnite",
        "Discord API"
    ]
    }
}

and here is the code for processing the data:

const string_data = JSON.stringify(fs.readFileSync('data/users.json', 'utf8'));
const data = JSON.parse(string_data);
console.log(typeof(data)); // <-- this line here shows the type of data as string
const results_array   = Object.values(data);

where fs is the file system package from npm.

Okay so fs.readFileSync returns a string so you dont need to use stringify

var fs = require('fs');
var read = fs.readFileSync('data/users.json', 'utf8');
console.log(read);
console.log(typeof(read));
const data = JSON.parse(read);
console.log(typeof(data));

You will see it returns an object

don't use JSON.stringify as it is further changing the string representation of JSON object. An example of what is happening is below

Imagine if you have a data in your file as shown below

{
   "key": "value"
}

When you read the file (using readFileSync ) and apply JSON.stringify , it is converted to a new string as shown below. You can notice that the double quotes are now escaped

"{\"key\": \"value\"}"

Now when you will parse it using JSON.parse then instead of getting the desired object , you are going to get back the same string you read from the file.

You are basically first performing and then undoing the stringify operation

This works for me:

const data = JSON.parse(fs.readFileSync('data/users.json', 'utf8'));
console.log(typeof(data)); // <-- this line here shows the type of data as OBJECT
const results_array   = Object.values(data);

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