I know this question has been answered many times before. But my string is a little different from others. Here's my data:
let str = "{'name':'joe', 'text':\"that's amazing\", 'registered':True, 'height':193, 'related':{'foo':'bar', 'some':'thing'}}"
and I am looking for something like: :
let obj = { name: 'joe',text:"that's amazing", registered:true, height: 193, related:{foo:'bar', some:'thing'}}
You can try using replace()
and JSON.parse()
:
let str = "{'name':'joe', 'registered':true, 'height':193, 'related':{'foo':'bar', 'some':'thing'}}"; let obj = str.replace(/'/g,'"'); obj = JSON.parse(obj); console.log(obj);
Update: Since you are having apostrophe in your string, you can try using JSON5 API which is compatible with the JSON API :
let str = "{'name':'joe', 'text':\"that's amazing\", 'registered':'True', 'height':193, 'related':{'foo':'bar', 'some':'thing'}}"; let obj = JSON5.parse(str); console.log(obj);
<script src="https://unpkg.com/json5@^2.0.0/dist/index.min.js"></script>
You can convert a JSON formatted string to object by parsing the string, like so: let obj = JSON.parse(str);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.