admin管理员组文章数量:1297076
I want to parse a JSON Object that contains some value as a json string, note that I don't know those fields previously, so I can't do something like
obj[key]=JSON.parse(obj[key])
. I am looking for an easy way to do that,
obj={
Name:"{\"FirstName\":\"Douglas\",\"LastName\":\"Crockford\"}"
}
And I want to get
{
Name:{
FirstName:"Douglas",
LastName:"Crockford"
}
}
I want to parse a JSON Object that contains some value as a json string, note that I don't know those fields previously, so I can't do something like
obj[key]=JSON.parse(obj[key])
. I am looking for an easy way to do that,
obj={
Name:"{\"FirstName\":\"Douglas\",\"LastName\":\"Crockford\"}"
}
And I want to get
{
Name:{
FirstName:"Douglas",
LastName:"Crockford"
}
}
Share
Improve this question
edited Dec 29, 2020 at 20:18
nadhem
asked Aug 9, 2017 at 23:45
nadhemnadhem
1881 gold badge5 silver badges22 bronze badges
0
6 Answers
Reset to default 1If you want to get paradoxical about it, you can handle arbitrarily nested versions of this scenario using the "reviver parameter". Start by stringifying
your object!
function parseJSON(k,v) {
try { return JSON.parse(v, parseJSON); }
catch(e) { return v; }
}
JSON.parse(JSON.stringify(obj), parseJSON);
Is that nifty, or is it just me?
We'll write a handy little utility which maps a function over object properties:
function mapObject(obj, fn) {
const result = {};
for (const prop in obj) result[prop] = fn(obj[prop], prop);
return result;
}
Now you can create an object with all the JSON values in the input parsed by just saying
mapObject(obj, JSON.parse)
If you want to guard against property values which are not valid JSON, then
function parseJSON(x) {
try { return JSON.parse(x); }
catch (e) { return x; }
}
and then
mapObject(obj, parseJSON)
You could use Object.keys(obj)
to get the property names to allow you to use JSON.parse()
You can always try/pass on every key:
a = {
a: 1,
b: JSON.stringify({a: 1, b: 2}),
c: 'asdf'
}
console.log(a);
new_a = {}
Object.keys(a).map((key) => {
try {
new_a[key] = JSON.parse(a[key]);
} catch(err) {
new_a[key] = a[key];
}
})
console.log(new_a);
You can simply loop over all the keys:
obj={
Name: "{\"FisrtName\":\"Douglas\",\"LastName\":\"Crockford\"}",
Other: "This isn't JSON"
};
for (var key in obj) {
try {
obj[key] = JSON.parse(obj[key]);
} catch(err) {
// ignore error, just leave it alone
}
}
console.log(obj);
I have succeeded with : jsonData['key']['value']
本文标签: javascriptParse JSON Object that contains Json stringStack Overflow
版权声明:本文标题:javascript - Parse JSON Object that contains Json string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741643583a2390057.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论