'How to parse string of objects into javascript object? [duplicate]
I get from db this string:
{ from: 15.00, to: 16.00 },
{ from: 16.00, to: 17.00 },
{ from: 17.00, to: 18.00 },
{ from: 18.00, to: 19.00 }
It is a string and json.parse not work in this case. Is it possible to convert this string to regular js object?
Solution 1:[1]
Your current database output isn't parsable because it isn't considered valid JSON. You have a few options to fix this issue:
Store your string in your database as a stringified object so that when you need to parse it, it can be done easily.
Use regex to reformat your string so that it is parsable using
JSON.parse. This involves making each key a string.You can "loosely" parse your JSON. However, this isn't recommended as it opens your javascript up to injection attacks and other vulnerabilities.
Reformatting your string:
const str = "{ from: 15.00, to: 16.00 },{ from: 16.00, to: 17.00 },{ from: 17.00, to: 18.00 },{ from: 18.00, to: 19.00 }",
parsable = str.replace(/(\w+):/g, '"$1":'),
obj = JSON.parse("[" +parsable +"]");
console.log(obj);
"Loosely" parsing your JSON with a Function constructor: - (Not recommended)
const str = "{ from: 15.00, to: 16.00 },{ from: 16.00, to: 17.00 },{ from: 17.00, to: 18.00 },{ from: 18.00, to: 19.00 }",
obj = (Function("return [" + str + "]"))();
console.log(obj);
Solution 2:[2]
It is already parsed in JavaScript JSON syntax, you just need to enclose it in "[]" square braces. and you can directly access it as it is already parsed. You can test for first object using...
objArray=[
{ from: 15.00, to: 16.00 },
{ from: 16.00, to: 17.00 },
{ from: 17.00, to: 18.00 },
{ from: 18.00, to: 19.00 }
];
console.log("From : " + objArray[0].from + " To : " + objArray[0].to);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
