admin管理员组

文章数量:1326478

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
Add a ment  | 

2 Answers 2

Reset to default 7

After 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 the undefined 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