简体   繁体   中英

how to json.stringify() a string

i have a complex object which is stored as a string in a text file

This is my data which i am reading from a text file

 [
 {
    name: "V",
    number: 20,
    coords: {
        "cn": { 
            points: [
                [23,32,32],
                [32,32,32]
            ], 
            B: "VC", 
            label: "ds"
        }
    }
}]

I want to convert this to a JSON string

Note:- I cant use eval function I have tried this JSON.stringify but i am getting this output:-

"   [\r\n     {\r\n        name: \"V\",\r\n        number: 20,\r\n        coords: {\r\n            \"cn\": { \r\n                points: [\r\n                    [23,32,32],\r\n                    [32,32,32]\r\n                ], \r\n                B: \"VC\", \r\n                label: \"ds\"\r\n            }\r\n        }\r\n    }]"

You can use combination of eval() and JSON.stringify() . eval() will convert it into valid JavaScript object and now you can use JSON.stringify() to convert it into JSON string.

 var str='[\\ {\\ name: "V",\\ number: 20,\\ coords: {\\ "cn": { \\ points: [\\ [23,32,32],\\ [32,32,32]\\ ], \\ B: "VC", \\ label: "ds"\\ }\\ }\\ }]'; document.write(JSON.stringify(eval(str)));

i don't know the reason for this! converting object-form-string to JSON-string but it's easy in your case:

 let object_form_string = `[ { name: "V", number: 20, coords: { "cn": { points: [ [23,32,32], [32,32,32] ], B: "VC", label: "ds" } } }]` let json_form_string = object_form_string.replace(/(name|number|coords|points|B|label)(?=:)/g, "\\"$&\\"") let obj_json = JSON.parse(`{"coordination": ${json_form_string}}`) // add {} to change array to object // add "coordination" (just an example) to access to data // read/write data (optional of course) let json = JSON.stringify(obj_json) console.log(json) console.log(`type of obj_json is: ${typeof obj_json}`) console.log(json_form_string) console.log(`name is: ${obj_json.coordination[0].name}`) console.log(`number is: ${obj_json.coordination[0].number}`)

enjoy and don't use eval()

If it is already stored as a string, is it not in JSON already? You shouldn't need to convert it anymore. That's why the \\r and \\n are appearing. You should not need to convert it anymore.

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