我对JavaScript不太了解,尝试执行从JSON文档开始创建另一个JSON文档的脚本会发疯:
(我将示例放入html文件中,并在Chrome上对其进行了调试,您可以执行相同的操作来对其进行测试):
<!DOCTYPE HTML>
<html>
<body>
<p>Before the script...</p>
<script>
function checkForNull(value) {
if (value instanceof Object && "@nil" in value) {
return null;
}
return value;
}
console.log("START")
var payload = JSON.parse(`
{
"Markets": {
"Market": {
"market_name": "Tambacounda Market N1",
"market_description": "Tambacounda Market N1",
"localization_id": 2,
"long": 13.776796,
"lat": -13.672198,
"country": "Senegal",
"regione": {
"@nil": "true"
},
"province": {
"@nil": "true"
},
"city": {
"@nil": "true"
},
"district": {
"@nil": "true"
},
"town": {
"@nil": "true"
},
"village": {
"@nil": "true"
},
"commodity": {
"el": [{
"commodity_details_id": 4,
"commodity_name_en": "Red onion",
"commodity_name": "Red onion",
"image_link": "Red_onion.jpg",
"today_avg_price": 20.1500,
"yesterday_avg_price": 33.3300,
"currency": "XOF",
"measure_unit": "kilogram",
"price_series_id": 1
}, {
"commodity_details_id": 6,
"commodity_name_en": "Green Beans",
"commodity_name": "Green Beans",
"image_link": "Green_Beans.jpg",
"today_avg_price": {
"@nil": "true"
},
"yesterday_avg_price": 778.0000,
"currency": "RWF",
"measure_unit": "kilogram",
"price_series_id": 17
}
]
}
}
}
}
`);
// create new response
var response = payload.Markets.Market;
console.log("RESPONSE: " + JSON.stringify(response));
// convert null values
response.regione = checkForNull(response.regione);
response.province = checkForNull(response.province);
response.city = checkForNull(response.city);
response.district = checkForNull(response.district);
response.town = checkForNull(response.town);
response.village = checkForNull(response.village);
// convert array of commodities into required HATEOS format
var commodity = new Array();
for (i = 0; i < response.commodity.el.length; ++i) {
var el = response.commodity.el[i];
var newEl = new Object();
newEl.commodity_name = el.commodity_name;
newEl.commodity.today_avg_price = el.today_avg_price;
newEl.commodity.yesterday_avg_price = el.yesterday_avg_price;
newEl.rel = "commodity_details";
newEl.href = "http://5.249.148.180:8280/commodity_details/" + el.commodity_details_id;
newEl.type = "GET";
commodity.push(newEl);
}
response.commodity = commodity;
console.log("END");
</script>
<p>...After the script.</p>
</body>
</html>
如您所见,原始文档已放入有效负载对象中。
问题发生在for循环中第一次迭代的这一行:
newEl.commodity.today_avg_price = el.today_avg_price;
并给出以下错误信息:
parse_json_market.html:97 Uncaught TypeError: Cannot set property 'today_avg_price' of undefined
at parse_json_market.html:97
如您所见,此JSON字段包含20.1500值
"today_avg_price": 20.1500,
为什么?问题是什么?我想念什么?如何解决此问题?
最佳答案
您只需在newEl.commodity.today_avg_price
之前添加此代码
newEl.commodity = new Object();
原因是因为
newEl
是object
,但是newEl.commodity
是undefined
。因此,必须在调用
newEl.commodity
之前将newEl.commodity.today_avg_price
设置为对象。FIDDLE