Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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    }]"
like image 642
bangali babu Avatar asked Oct 19 '22 01:10

bangali babu


1 Answers

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)));
like image 154
Pranav C Balan Avatar answered Nov 01 '22 13:11

Pranav C Balan