Reputation: 305
I have such strings which I get by manipulating the DOM. how can I convert them to javascript objects, so that I can later stringify them? please advise.
can I use JSON.parse with reviver?
str = "age: 65, name: "Jay", smoker: false"
thanks
Upvotes: 0
Views: 170
Reputation: 4600
Let's start from beginning:
Your string has invalid json syntax: "age: 65, name: "Jay", smoker: false"
This is a valid json syntax: {"age": 65, "name": "Jay", "smoker": false}
After turn this valid, you could do just a simple parse:
var json = JSON.parse({"age": 65, "name": "Jay", "smoker": false});
However, do you need to convert your invalid string to a valid JS Object, right?
We can achieve it in that way:
var str = "age: 65, name: \"Jay\", smoker: false";
str = str.split(',').map((str) => str.trim().substring(0, str.length).replace(': ', ':'));
var obj = {};
for (var i = 0; i < str.length; i++) {
var split = str[i].split(':');
// "boolean" to boolean
split[1] = split[1] === "true" ? true : split[1] === "false" ? false : split[1];
// ""string"" to "string"
split[1] = typeof split[1] === 'string' ? split[1].replace(/['"]+/g, '') : split[1];
obj[split[0]] = split[1];
}
// results valid obj: { age: "6", name: "Jay", smoker: false }
Using this object, you can easily do JSON.stringify(obj)
to get a valid json.
Of course, if you change your string structure, this functions will need re-work.
Upvotes: 1