在JSON中搜索对象

Joh*_*per 3 javascript 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;"
    }
}}    
Run Code Online (Sandbox Code Playgroud)

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

rob*_*les 8

通过键迭代:(增强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]);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

工作演示@ http://jsfiddle.net/roberkules/JFEMH/