在JSON中搜索对象 [英] Searching for an Object inside the JSON

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

问题描述

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}    

这是我的JSON字符串。现在我想在这个JSON中搜索名称,然后显示结果......

Here is my JSON String. Now i want to search for name in this JSON and then display the results...

推荐答案

通过键迭代:
(对Amit Gupta答案的增强)

Iterate through the keys: (enhancement to Amit Gupta's answer)

var result = [];
getNames(data, "name");
document.write("result: " + result.join(", "));

function getNames(obj, name) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            if ("object" == typeof(obj[key])) {
                getNames(obj[key], name);
            } else if (key == name) {
                result.push(obj[key]);
            }
        }
    }
}

工作demo @ http://jsfiddle.net/roberkules/JFEMH/

const data = {
  "widget": {
    "debug": "on",
    "window": {
      "title": "Sample Konfabulator Widget",
      "name": "main_window",
      "width": 500,
      "height": 500
    },
    "image": {
      "src": "Images/Sun.png",
      "name": "sun1",
      "hOffset": 250,
      "vOffset": 250,
      "alignment": "center"
    },
    "text": {
      "data": "Click Here",
      "size": 36,
      "style": "bold",
      "name": "text1",
      "hOffset": 250,
      "vOffset": 100,
      "alignment": "center",
      "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
  }
}

let result = [];
getNames(data, "title");
document.write("result: " + result.join(", "));

function getNames(obj, name) {
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      if ("object" == typeof(obj[key])) {
        getNames(obj[key], name);
      } else if (key == name) {
        result.push(obj[key]);
      }
    }
  }
}

这篇关于在JSON中搜索对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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