admin管理员组文章数量:1326299
I need to identify if my JSON feed has child key/value pairs and handle them differently. what i mean is:
{
"dashboard" :[
{
"name": "",
"image": "",
"description":"",
"linkurl":"" },
{
"name": "",
"image": "",
"description":"",
"linkurl":""
},
"related" : [
{
"name": "",
"image": "",
"description":"",
"linkurl":""
},
{
"name": "",
"image": "",
"description":"",
"linkurl":""
}]
]
How do i identify that this JSON has those child ("related") key/value pairs?
I need to identify if my JSON feed has child key/value pairs and handle them differently. what i mean is:
{
"dashboard" :[
{
"name": "",
"image": "",
"description":"",
"linkurl":"" },
{
"name": "",
"image": "",
"description":"",
"linkurl":""
},
"related" : [
{
"name": "",
"image": "",
"description":"",
"linkurl":""
},
{
"name": "",
"image": "",
"description":"",
"linkurl":""
}]
]
How do i identify that this JSON has those child ("related") key/value pairs?
Share Improve this question edited Aug 18, 2011 at 7:55 Reporter 3,9485 gold badges35 silver badges49 bronze badges asked Aug 18, 2011 at 7:50 amitamit 10.2k23 gold badges76 silver badges125 bronze badges 1- 3 jsonlint. Your JSON is mal-formed – timdream Commented Aug 18, 2011 at 7:54
2 Answers
Reset to default 7After parsing the JSON string into a JavaScript object (see greengit's answer), you have three options:
typeof obj.related !== 'undefined'
obj.related !== undefined
. Be careful when using theundefined
variable, it can be changed by other scripts. If you are using it, make sure to wrap your code in anonymous function that sets it to a correct value - see Javascript Garden about that, under "Handling Changes to the Value of undefined"'related' in obj
IIRC, using in
should be the fastest
update I remember it the other way around - in
is the slowest way of doing that, by a large margin (98%!). Also, using typeof obj.key !== 'undefined'
is much faster than obj.key !== undefined
(the latter is 80% slower). See http://jsperf./in-vs-not-undefined.
Convert JSON into a JS object and see if what you want is undefined
.
var obj = JSON.parse(json_string);
if ( obj.related == undefined ) {
...
本文标签: javascriptCheck for child keyvalue pairs in JSONStack Overflow
版权声明:本文标题:javascript - Check for child keyvalue pairs in JSON - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742206624a2432934.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论