javascript 在 JSON 中搜索对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6110327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:30:54  来源:igfitidea点击:

Searching for an Object inside the JSON

javascriptjson

提问by John Cooper

{"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;"
    }
}}    

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

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

回答by roberkules

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

遍历键:(增强 Amit Gupta 的答案)

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]);
            }
        }
    }
}

Working demo @ http://jsfiddle.net/roberkules/JFEMH/

工作演示@ 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]);
      }
    }
  }
}

回答by Mohammad Adil

You can use Jquery to parse JSON

您可以使用 Jquery 来解析 JSON

 $.ajax({
    type: "POST",
    url: "../JSON Source",
    success: function(msg) {
    var obj=jQuery.parseJSON(msg);
    if(obj.debug== "on"){
        //do anything

. . . . .

. . . . .

回答by Amit Gupta

You can iterate recursively to all the objects inside the given object.

您可以递归地迭代给定对象内的所有对象。

    s = "";

    function recursiveSearch(obj, name){
       if(typeof(obj)==="object" {
         for(var key in obj) {
            if (obj.hasOwnProperty(key)) {
              s += ":" + recursiveSearch(obj[key], name);
            }  
       } else if( typeof(obj["name"] != 'undefined') {
         s += ":" + obj["name"];

    }

Output will be colon separated values with key "name"

输出将是冒号分隔的值,键为“name”

回答by Nix

I would recommend using this JSON extension injson. It allows for you to use JQuery to search for a key in a JSON object.

我建议使用这个 JSON 扩展injson。它允许您使用 JQuery 搜索 JSON 对象中的键。

回答by Hakan Bilgin

Instead of writing custom search functions, you can use DefiantJS (http://defiantjs.com) which enables queries on JSON structures with XPath expressions. Example:

您可以使用 DefiantJS ( http://defiantjs.com),而不是编写自定义搜索函数,它可以使用XPath 表达式对 JSON 结构进行查询。例子:

    var 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;"
        }
     }
  },
res = JSON.search( data, '//image[name]' );

console.log( res[0].name );

Here is a working fiddle:
http://jsfiddle.net/hbi99/CRTz9/

这是一个工作小提琴:http:
//jsfiddle.net/hbi99/CRTz9/

DefiantJS extends the global object JSON with the method "search" and returns an array with the matches (empty array if no matches were found).

DefiantJS 使用“搜索”方法扩展全局对象 JSON,并返回一个包含匹配项的数组(如果没有找到匹配项,则为空数组)。