我有一个从Web服务返回的JSON对象,我想从对象中提取元素,特别是第一个元素id
?
[{"id":2,"type":"Asset",
"assetNumber":"13723",
"macAddress":null,"networkName":
"13723imsmid8","model":
{"id":16,"type":"Model",
"modelName":"M73","manufacturer":
{"id":10,"type":"Manufacturer"}}},
{"id":3556,"type":"Asset",
"assetNumber":"13723",
"macAddress":null,
"networkName":null,
"model":{"id":16,"type":"Model",
"modelName":"M73","manufacturer":
{"id":10,"type":"Manufacturer"}}},
{"id":7196,"type":"Asset",
"assetNumber":"13723",
"macAddress":null,"networkName":null,
"model":{"id":16,"type":"Model",
"modelName":"M73","manufacturer":
{"id":10,"type":"Manufacturer"}}},
{"id":9720,"type":"Asset",
"assetNumber":"13723",
"macAddress":null,"networkName":null,
"model":{"id":16,"type":"Model","modelName":"M73",
"manufacturer": {"id":10,"type":"Manufacturer"}}},
{"id":11689,"type":"Asset",
"assetNumber":"13723",
"macAddress":null,
"networkName":null,"
model":{"id":68,"type":"Model",
"modelName":"POC-W211","manufacturer":
{"id":19,"type":"Manufacturer"}}},{"id":11906,"type":"Asset",
"assetNumber":"13723",
"macAddress":null,
"networkName":null,
"model":{"id":71,"type":"Model",
"modelName":"OptiPlex 780",
"manufacturer":{"id":5,"type":"Manufacturer"}}}]
答案 0 :(得分:0)
您可以迭代数据数组并使用数组映射函数提取ID:
const data = [{"id":2,"type":"Asset","assetNumber":"13723","macAddress":null,"networkName":"13723imsmid8","model":{"id":16,"type":"Model","modelName":"M73","manufacturer":{"id":10,"type":"Manufacturer"}}},{"id":3556,"type":"Asset","assetNumber":"13723","macAddress":null,"networkName":null,"model":{"id":16,"type":"Model","modelName":"M73","manufacturer":{"id":10,"type":"Manufacturer"}}},{"id":7196,"type":"Asset","assetNumber":"13723","macAddress":null,"networkName":null,"model":{"id":16,"type":"Model","modelName":"M73","manufacturer":{"id":10,"type":"Manufacturer"}}},{"id":9720,"type":"Asset","assetNumber":"13723","macAddress":null,"networkName":null,"model":{"id":16,"type":"Model","modelName":"M73","manufacturer":{"id":10,"type":"Manufacturer"}}},{"id":11689,"type":"Asset","assetNumber":"13723","macAddress":null,"networkName":null,"model":{"id":68,"type":"Model","modelName":"POC-W211","manufacturer":{"id":19,"type":"Manufacturer"}}},{"id":11906,"type":"Asset","assetNumber":"13723","macAddress":null,"networkName":null,"model":{"id":71,"type":"Model","modelName":"OptiPlex 780","manufacturer":{"id":5,"type":"Manufacturer"}}}];
const ids = data.map(item => item.id)
// returns an array of ids: [2, 10, 16, ...]
答案 1 :(得分:0)
或者,
var json = [{"id":2,"type":"Asset","assetNumber":"13723","macAddress":null,"networkName":"13723imsmid8","model":{"id":16,...';
var p = 0;
do {
p=json.indexOf('"id":',p)+5;
n=json.indexOf(',',p);
alert(json.substr(p,(n-p)));
}
while (json.indexOf('"id":',p)>0);