如何读取这些数组? [英] how to read these to array?
本文介绍了如何读取这些数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
items:[
{
id:1,
obj:{
json: 1.json,
js:1. js,
css:1.css,
text:1.txt,
}
},
{
id:2,
obj:{
json:2。 json,
js:2.js,
css:2.css,
text:2.txt,
}
}
]
如果我传递id = 1那么它应该显示
json :1.json,
js:1. js,
css:1.css,
text:1.txt,这个
解决方案
要解析JSON值,请使用JSON.parse
。然后遍历所有项目以查找所需的数据:
var items = JSON 跨度> .parse(yourJsonString).items;
var idToSearch = 1跨度>;
for ( var i = 0 ; i< items.length; i ++){
if (items [i] .id == idToSearch){
var foundData = items [i] .obj;
// 现在显示您要显示的数据
}
}
此外,您的JSON字符串无效。之后有一个没有数据的逗号,外部对象应该包含在{}
大括号中。因此,这些数据是有效的:
{
项目:[
{
id: 1,
obj:{
json: 1.json,
js: 1.js,
css: 1.css,
text: 1.txt
}
},
{
id: 2,
obj :{
json: 2.json,
js: 2.js,
css: 2.css,
text: 2.txt
}
}
]
}
"items":[
{
"id":"1",
"obj":{
"json":"1.json",
"js":"1.js",
"css":"1.css",
"text":"1.txt",
}
},
{
"id":"2",
"obj":{
"json":"2.json",
"js":"2.js",
"css":"2.css",
"text":"2.txt",
}
}
]
if i passs id=1 then it should display
"json":"1.json",
"js":"1.js",
"css":"1.css",
"text":"1.txt", this
解决方案
To parse a JSON value, useJSON.parse
. Then loop over all items to find the data you need:
var items = JSON.parse(yourJsonString).items; var idToSearch = "1"; for (var i = 0; i < items.length; i++) { if (items[i].id == idToSearch) { var foundData = items[i].obj; // now display foundData where you want to display it } }
Also, your JSON string is invalid. There is a comma without data after it, and the outer object should be wrapped within{}
braces. So, this data is valid:
{ "items": [ { "id": "1", "obj": { "json": "1.json", "js": "1.js", "css": "1.css", "text": "1.txt" } }, { "id": "2", "obj": { "json": "2.json", "js": "2.js", "css": "2.css", "text": "2.txt" } } ] }
这篇关于如何读取这些数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文