我必须从JSON文件中检索数据,然后将其分配给数组。但是我收到了一个错误
"无法设置属性' ref'未定义"。
将JSON转换为关联数组或对象。
var items2=[[]];
$.getJSON("results.json", function( data ) {
$.each( data, function( key, val ) {
if(key=="items")
{
$.each(val,function(keyScd,valScd)
{
$.each(valScd,function(keyTrd,valTrd)
{
var ref=JSON.stringify(valTrd.ref).slice(1,-1);
var prix=JSON.stringify(valTrd.prix).slice(1,-1);
var taille=JSON.stringify(valTrd.taille).slice(1,-1);
items2[keyScd][keyTrd]["ref"]=ref;
items2[keyScd][keyTrd]["prix"]=prix;
items2[keyScd][keyTrd]["taille"]=taille;
});
});
}
else
{
items2[key]=val;
}
});
});
这是我的JSON
{
"items":[
[
{
"ref":"cpe-zfmmpx23",
"nomc":"1",
"description":"yellow sofa",
"dispo":"1",
"prix":"300",
"taille":"standard",
"couleur":"jaune"
},
{
"ref":"cpe-zfmmpx23",
"nomc":"2",
"description":"yellow sofa",
"dispo":"1",
"prix":"400",
"taille":"0.5mH,2mW",
"couleur":"red"
}
]
],
"buildNumber":"fa36b5153f33240a111e6dc336a70"
}
答案 0 :(得分:2)
您应该能够映射元素。这就是你要追求的吗?
var temp = `{"items":[[{"ref":"cpe-zfmmpx23","nomc":"1","description":"yellow sofa","dispo":"1","prix":"300","taille":"standard","couleur":"jaune"},{"ref":"cpe-zfmmpx23","nomc":"2","description":"yellow sofa","dispo":"1","prix":"400","taille":"0.5mH,2mW","couleur":"red"}]],"buildNumber":"fa36b5153f33240a111e6dc336a70"}
`;
var data = JSON.parse(temp);
var items2;
if (data.items) {
items2 = $.map(data.items, function(items) {
return $.map(items, function(item) {
return {
ref: item.ref.slice(1, -1),
prix: item.prix.slice(1, -1),
taille: item.taille.slice(1, -1)
};
});
});
}
console.log(items2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 1 :(得分:-1)
这是另一种方法,不需要在那里使用jquery:
const json = '{"items":[[{"ref":"cpe-zfmmpx23","nomc":"1","description":"yellow sofa","dispo":"1","prix":"300","taille":"standard","couleur":"jaune"},{"ref":"cpe-zfmmpx23","nomc":"2","description":"yellow sofa","dispo":"1","prix":"400","taille":"0.5mH,2mW","couleur":"red"}]],"buildNumber":"fa36b5153f33240a111e6dc336a70"}';
const newJson = JSON.parse(json);
(newJson.items).forEach((data) => {
data.forEach((newData) => {
console.log(newData.ref)
});
});
&#13;