Reputation: 329
So I am trying to use a really weird API, the call gets a response of a javascript eval code, this code contains the javascript object which I trimmed in this fashion:
var obj = resp.substring(0, resp.length-9);
Thus getting the object like this:
"{name: "Jon", code: 123, info: [{blah blah}, {blah blah}]}"
This "object" is recognized as a string and I am unable to extract it.
JSON parsing won't works as it is no JSON.
new Object(obj); won't aswell, it outputs the object trimmed by every character.
Any suggestions?
EDIT: 1 So replacing every <"> with a <'> does not solve the problem. Further JSON-parsing the result prints an error at position 1 with unexpected token n at position 1.
Keep trying new things.
Upvotes: 3
Views: 105
Reputation: 1361
Eval function invokes many serious security problems in your code. Instead what you can do is, since you got a string, just replace every double quotes(") with a single quote inside the string. And then parse it.
JSON.parse only fails when the javascript parser is not getting a perfect object level string.
Code:
var objStr = "{name: "Jon", code: 123, info: [{blah blah}, {blah blah}]}";
var obj = JSON.parse(objStr.replace(/"/g, "'"));
Upvotes: 1
Reputation: 678
You really should be cautious about using eval when getting data from an external source.
I'd suggest trying to fix the string to be proper regex instead of calling eval, one way of doing this would be to create a regex which will match the property names and surround them in quotations:
let a = `{name: "Jon", code: 123, info: [{}, {}]}`;
let obj = JSON.parse(a.replace(/(\w|\d)+(?=\:)/g, "\"$&\""));
console.log(obj)
Obviously this example would need improving if you can expect to see colons inside your object's property values
Upvotes: 1