5

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    }]"
Dmitry Reutov
  • 2,995
  • 1
  • 5
  • 20
bangali babu
  • 117
  • 1
  • 2
  • 9

2 Answers2

2

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)));
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

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()

Iliya
  • 11
  • 2