将json对象转换为字符串

时间:2016-02-08 07:10:28

标签: javascript jquery json

我按如下方式生成json对象,我需要在javascript中迭代并获取其中的值。

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

如果我将其字符串化,我将获得以下值,

[[{"K":"43800001","D":"Resident Demand Deposit"},{"K":"43800099","D":"Not Applicable"},
{"K":"43800014","D":"Cash"},
{"K":"43800012","D":"Income and Expenditure"},
{"K":"43800011","D":"Other Liabilities"},
{"K":"43800010","D":"Other Assets"},
{"K":"43800009","D":"Bankers"},
{"K":"43800008","D":"Bar"},
{"K":"43800007","D":"DD"},
{"K":"43800006","D":"HO"},
{"K":"43800005","D":"Advance"},
{"K":"43800004","D":"Investments"},
{"K":"43800003","D":"Bills"},
{"K":"43800002","D":"Resident Term Deposit"}]]

它包含14个记录对,其中包含K代码,而D代表代码描述。我需要迭代每个K,D对数据。

我尝试如下, reusult持有14 [object object]值,如上所示。

result[0].K.toString();
result[0].D.tostring();

我收到类型错误。

4 个答案:

答案 0 :(得分:0)

我建议使用stringify。

示例:

JSON.stringify({ x: 5 })

在您的情况下,您可以将整个对象或数组存储在变量中并将其传递给stringify方法:

示例:

var data = { x: 5 };

JSON.stringify(data) 

输出将如下:

'{"x":5}'

希望这会对你有所帮助:)。

答案 1 :(得分:0)

  

使用JSON.stringify(obj),此方法将JavaScript值转换为JSON字符串。

修改

您不需要将值转换为字符串,因为它们的类型为string

试试这个:



var obj = [{
  "K": "43800001",
  "D": "Resident Demand Deposit"
}, {
  "K": "43800099",
  "D": "Not Applicable"
}, {
  "K": "43800014",
  "D": "Cash"
}, {
  "K": "43800012",
  "D": "Income and Expenditure"
}, {
  "K": "43800011",
  "D": "Other Liabilities"
}, {
  "K": "43800010",
  "D": "Other Assets"
}, {
  "K": "43800009",
  "D": "Bankers"
}, {
  "K": "43800008",
  "D": "Bar"
}, {
  "K": "43800007",
  "D": "DD"
}, {
  "K": "43800006",
  "D": "HO"
}, {
  "K": "43800005",
  "D": "Advance"
}, {
  "K": "43800004",
  "D": "Investments"
}, {
  "K": "43800003",
  "D": "Bills"
}, {
  "K": "43800002",
  "D": "Resident Term Deposit"
}];
var html = '';
obj.forEach(function(item) {
  html += '<div>Code: ' + item.K + ' Description: ' + item.D + '</div>'
});
document.body.innerHTML = html;
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你可以遍历每一对K&amp; D喜欢以下。

var result = [[
    { "K": "43800001", "D": "Resident Demand Deposit" },
    { "K": "43800099", "D": "Not Applicable" },
    { "K": "43800014", "D": "Cash" }
]];

$.each(result[0], function () {
    console.log(this.K);
    console.log(this.D);
})

答案 3 :(得分:-1)

试试这个:

$.each(obj, function(i, item) {
   var data_k = item.K;
   var data_d = item.D;
});