Javascript 如何将json项推送到数组?
我有以下json:Javascript 如何将json项推送到数组?,javascript,Javascript,我有以下json: [ { "ID": 1, "Lat": 39.21988, "Lng": 9.124741, "Date": "01.01.2020", "Time": "08:54:00 AM", "Plastic": 0.156, "Metal": 0.321, "Paper": 0.098, "Glass": 0.085 }, { "ID": 1, "Lat": 39.21988,
[
{
"ID": 1,
"Lat": 39.21988,
"Lng": 9.124741,
"Date": "01.01.2020",
"Time": "08:54:00 AM",
"Plastic": 0.156,
"Metal": 0.321,
"Paper": 0.098,
"Glass": 0.085
},
{
"ID": 1,
"Lat": 39.21988,
"Lng": 9.124741,
"Date": "01.01.2020",
"Time": "10:15:23 AM",
"Plastic": 0.078,
"Metal": 0.652,
"Paper": 0.085,
"Glass": 0.078
},
我试过:
var str = JSON.stringify(<?php echo $contents; ?>, null, 2);
$.each (str, function (i) {
console.log(str[i]["lat"]);
});
如果要对JSON进行迭代,请不要将其字符串化 如果您想要使用
JSON.parse
,因为它可以作为字符串从PHP中获得
大概是这样的:
var array = <?php echo $contents; ?>;
/// or if it's coming as a string from php
var array = JSON.parse(<?php echo $contents; ?>);
array.forEach((thing) => {
coords.push({thing['lat'], thing['lng']});
console.log(thing.lat);
});
var数组=;
///或者如果它是来自php的字符串
var array=JSON.parse();
array.forEach((thing)=>{
coords.push({thing['lat'],thing['lng']});
console.log(thing.lat);
});
您可以这样尝试
var jsonObj = [
{
"ID": 1,
"Lat": 39.21988,
"Lng": 9.124741,
"Date": "01.01.2020",
"Time": "08:54:00 AM",
"Plastic": 0.156,
"Metal": 0.321,
"Paper": 0.098,
"Glass": 0.085
},
{
"ID": 1,
"Lat": 39.21988,
"Lng": 9.124741,
"Date": "01.01.2020",
"Time": "10:15:23 AM",
"Plastic": 0.078,
"Metal": 0.652,
"Paper": 0.085,
"Glass": 0.078
}];
var coords = jsonObj.map(function(item) {
return (item.Lat + "," + item.Lng);
});
console.log(coords); // ["39.21988,9.124741", "39.21988,9.124741"]
如果您将JSON作为字符串,那么您可以使用
JSON.parse(“yourString”)
获取JSON对象。对我来说,这听起来更像是一个PHP问题,而不是JavaScript问题。@Ryuno Ki为什么?json是从PHP中使用的,但它是纯jsonnow@CalvinNunes是的,问题的最后一段代码你需要做一些类似于arrayOfYours.push的事情({lat:str[I]['lat'],lng:str[I]['lng'])@JDunken确实是,但由于某些原因,我的循环是错误的谢谢,你也可以提供一个代码示例吗?谢谢,但它给了我控制台Uncaught SyntaxError:Unexpected token'['
({lat:parseFloat(i.lat),lng:parseFloat(i.lng)});我跳到了你发起的聊天,但是你没有出现
var jsonObj = [
{
"ID": 1,
"Lat": 39.21988,
"Lng": 9.124741,
"Date": "01.01.2020",
"Time": "08:54:00 AM",
"Plastic": 0.156,
"Metal": 0.321,
"Paper": 0.098,
"Glass": 0.085
},
{
"ID": 1,
"Lat": 39.21988,
"Lng": 9.124741,
"Date": "01.01.2020",
"Time": "10:15:23 AM",
"Plastic": 0.078,
"Metal": 0.652,
"Paper": 0.085,
"Glass": 0.078
}];
var coords = jsonObj.map(function(item) {
return (item.Lat + "," + item.Lng);
});
console.log(coords); // ["39.21988,9.124741", "39.21988,9.124741"]