我一直在搞这样的事情但在终端 executed
时未定义,
"Line1": "---------------------Project Information---------------------",
`在我>之后,我怎样才能正确地在终端中打印虚线?运行我的js文件解析下面的json数据?
{
"Line1": "---------------------Project Information---------------------",
"CustomerNumber1": "Customer Number: 1125\n",
"CustomerName1": "Customer Name: John Smith\n",
"PackageNumber1": "Package Number: 011\n",
"Trip Cost1": "Trip Cost: $3760\n",
"Line2": "------------------------------------------------------------",
"CustomerNumber2": "Customer Number: 1234\n",
"CustomerName2": "Customer Name: Jerry Smith\n",
"PackageNumber2": "Package Number: 011\n",
"Trip Cost2": "Trip Cost: $2899\n",
"Line3": "------------------------------------------------------------",
"CustomerNumber3": "Customer Number: 1324\n",
"CustomerName3": "Customer Name: Andreas Smith\n",
"PackageNumber3": "Package Number: 011\n",
"Trip Cost3": "Trip Cost: $1199\n",
"Line4": "------------------------------------------------------------"
}
答案 0 :(得分:4)
您的JSON数据应该只存储原始数据,而不是任何格式。在您的情况下,您应该有一个对象数组,每个对象都有属性:
[
{
"CustomerNumber": 1125,
"CustomerName": "John Smith",
"PackageNumber": "011",
"Trip Cost": 3760
},
{
"CustomerNumber": 1234,
"CustomerName": "Jerry Smith",
"PackageNumber": "011",
"Trip Cost": 2899
},
{
"CustomerNumber": 1324,
"CustomerName": "Andreas Smith",
"PackageNumber": "011",
"Trip Cost": 1199
}
]
然后,您可以在打印数据时让代码添加格式:
var list = JSON.parse(/* your JSON string */);
console.log("---------------------Project Information---------------------");
for (var i = 0; i < list.length; i++) {
var obj = list[i];
console.log("Customer Number: "+obj["CustomerNumber"]);
console.log("Customer Name: "+obj["CustomerName"]);
console.log("Package Number: "+obj["PackageNumber"]);
console.log("Trip Cost: $"+obj["Trip Cost"]);
console.log("------------------------------------------------------------");
}
var list = [
{
"CustomerNumber": 1125,
"CustomerName": "John Smith",
"PackageNumber": "011",
"Trip Cost": 3760
},
{
"CustomerNumber": 1234,
"CustomerName": "Jerry Smith",
"PackageNumber": "011",
"Trip Cost": 2899
},
{
"CustomerNumber": 1324,
"CustomerName": "Andreas Smith",
"PackageNumber": "011",
"Trip Cost": 1199
}
];
console.log("---------------------Project Information---------------------");
for (var i = 0; i < list.length; i++) {
var obj = list[i];
console.log("Customer Number: "+obj["CustomerNumber"]);
console.log("Customer Name: "+obj["CustomerName"]);
console.log("Package Number: "+obj["PackageNumber"]);
console.log("Trip Cost: $"+obj["Trip Cost"]);
console.log("------------------------------------------------------------");
}
&#13;