Job*_*ong 5 javascript regex recursion jquery json
我有一个可变深度的JSON文档.一个例子:
[
{
"type": "firsttype",
"text": {
"id": "content"
}
}
]
Run Code Online (Sandbox Code Playgroud)
我想要做的是检索某些键的值,比方说text.由于我不知道这些密钥在.JSON中可能出现在哪里,我需要使用递归函数.然后我尝试在HTML文件中显示这些键和值.
我在这里有一个初步的尝试:
$.getJSON("file.json", function getText (oValue, sKey) {
links = [];
if (typeof oValue == "object" || typeof oValue == "array") {
for (i in oValue) {
getText (oValue [i], i);
}
} else {
links.push ( "<li id='" + oValue + "'>" + sKey + "</li>" );
}
$( "<ul/>", {
"class": "my-new-list",
html: links.join( "" )
}).appendTo( "body" );
});
Run Code Online (Sandbox Code Playgroud)
当我在本地或远程或加载页面时python -m SimpleHTTPServer,我没有错误,页面上没有任何内容.我究竟做错了什么?我已将所有JS包含在$.getJSON调用中,因此不会出现异步问题.
在将来,我还想包括一个regexp检查,以便我可以使用某个字符串提取值,例如/http/.最好的方法是什么?
由于其他答案涵盖了您应该考虑的大部分内容,我想我只会针对您的实际问题发布一个解决方案。:)
您想要遍历任意 JSON 并搜索特定键,并且可能对其值有条件。然后您想要返回指定键的所有值(如果指定,则通过您的条件)。
假设您有以下 json:
{
"hello": "some text",
"object": {
"key1": "hello!",
"key2": "Bye!"
},
"array": [{
"some_key1": "blah blah blah",
"some_key2": 24
}, {
"some_key1": "ghiojd",
"some_key2": 13
}],
"numeric_array": [2, 3, 4, 5]
}
Run Code Online (Sandbox Code Playgroud)
此代码片段将搜索上面的 json 来查找some_key1其值以以下开头的内容blah:
{
"hello": "some text",
"object": {
"key1": "hello!",
"key2": "Bye!"
},
"array": [{
"some_key1": "blah blah blah",
"some_key2": 24
}, {
"some_key1": "ghiojd",
"some_key2": 13
}],
"numeric_array": [2, 3, 4, 5]
}
Run Code Online (Sandbox Code Playgroud)
function regexpConditionFactory(regex) {
return function(value) { return regex.test(value); };
}
function searchObjectForKey(obj, key, condition, result) {
if ($.isPlainObject(obj)) {
if (obj.hasOwnProperty(key)) {
if (!condition || ($.isFunction(condition) && condition(obj[key])))
result.push(obj[key]);
}
}
if ($.isPlainObject(obj) || $.isArray(obj)) {
for (var k in obj) {
if (obj.hasOwnProperty(k))
searchObjectForKey(obj[k], key, condition, result);
}
}
}
$.getJSON('file.json', function(data) {
var res = [];
searchObjectForKey(data, 'some_key1', regexpConditionFactory(/^blah/), res);
$('<ul/>', {
'class': 'my-new-list',
'html': res.map(function(value) { return '<li>' + value + '</li>'; }).join('')
}).appendTo('body');
});Run Code Online (Sandbox Code Playgroud)