检查JSON中的子键/值对 [英] Check for child key/value pairs in JSON

查看:87
本文介绍了检查JSON中的子键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定JSON供稿是否具有子键/值对,并以不同的方式处理它们.我的意思是:

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":""
        }]
  ]

我如何识别此JSON具有那些子(相关")键/值对?

How do i identify that this JSON has those child ("related") key/value pairs?

推荐答案

将JSON字符串解析为JavaScript对象(请参见greengit的答案)之后,您可以使用以下三种选择:

After parsing the JSON string into a JavaScript object (see greengit's answer), you have three options:

  • typeof obj.related !== 'undefined'
  • obj.related !== undefined.使用undefined变量时要小心,它可以被其他脚本更改.如果正在使用它,请确保将代码包装在将其设置为正确值的匿名函数中-请参见 Javascript花园,在处理未定义的值的更改"下
  • 'related' in obj
  • 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,使用in应该是最快的

IIRC, using in should be the fastest

更新我还记得另一种方式-in是最慢的 方式(98%!).同样,使用typeof obj.key !== 'undefined'obj.key !== undefined快得多(后者要慢80%).参见 http://jsperf.com/in-vs-not-undefined .

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.com/in-vs-not-undefined.

这篇关于检查JSON中的子键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆