我是Node.js的新手,这是我的示例json格式数据。我想将它们拆分为json格式,并需要获取tid值。在node.js中,我尝试使用JSON.parse(data),但发生了错误(由于[]符号)。 有没有一种简单的方法可以将它们拆分为json格式并获取tid值?
[{"date":1535624757,"date_ms":1535624757427,"amount":90.389717,"price":0.00860497,"type":"buy","tid":251916659},{"date":1535624757,"date_ms":1535624757428,"amount":99.428689,"price":0.00860497,"type":"buy","tid":251916662},{"date":1535624757,"date_ms":1535624757469,"amount":384.65968,"price":0.00860497,"type":"buy","tid":251916663}]
答案 0 :(得分:2)
似乎您正在尝试使用Javascript对象而不是包含JSON编码数据的字符串。考虑直接使用该对象。例如,您可以使用for
循环来迭代data
的元素,如下所示:
const data = [ {"date":1535624757,"date_ms":1535624757427,"amount":90.389717,"price":0.00860497,"type":"buy","tid":251916659},{"date":1535624757,"date_ms":1535624757428,"amount":99.428689,"price":0.00860497,"type":"buy","tid":251916662},{"date":1535624757,"date_ms":1535624757469,"amount":384.65968,"price":0.00860497,"type":"buy","tid":251916663}];
for (var i = 0; i < data.length; i++) {
console.log(data[i].tid);
}
答案 1 :(得分:2)
JSON.parse
带有一个字符串变量,[{"date":1535624757,"date_ms":1535624757427,"amount":90.389717,"price":0.00860497,"type":"buy","tid":251916659},{"date":1535624757,"date_ms":1535624757428,"amount":99.428689,"price":0.00860497,"type":"buy","tid":251916662},{"date":1535624757,"date_ms":1535624757469,"amount":384.65968,"price":0.00860497,"type":"buy","tid":251916663}]
您编写的这段代码是对象变量。
您可以使用此
var data = JSON.parse('[{"date":1535624757,"date_ms":1535624757427,"amount":90.389717,"price":0.00860497,"type":"buy","tid":251916659},{"date":1535624757,"date_ms":1535624757428,"amount":99.428689,"price":0.00860497,"type":"buy","tid":251916662},{"date":1535624757,"date_ms":1535624757469,"amount":384.65968,"price":0.00860497,"type":"buy","tid":251916663}]')
console.log(data)
答案 2 :(得分:0)
由于您发布的数组在JavaScript程序的上下文中是 not JSON(尽管它是valid standalone JSON document),所以假设data
是您的值数组:
const data = [{
"date":1535624757,
"date_ms":1535624757427,
"amount":90.389717,
"price":0.00860497,
"type":"buy",
"tid":251916659
}, {
"date":1535624757,
"date_ms":1535624757428,
"amount":99.428689,
"price":0.00860497,
"type":"buy",
"tid":251916662
}, {
"date":1535624757,
"date_ms":1535624757469,
"amount":384.65968,
"price":0.00860497,
"type":"buy",
"tid":251916663
}];
您可以像这样拉出提示:
const tids = data.map(e => e.tid);
提示:
[ 251916659, 251916662, 251916663 ]
如果您想将tid作为JSON字符串,则可以使用JSON.stringify:
const jsonTids = JSON.stringify(tids);
jsonTids:
'[251916659,251916662,251916663]'
答案 3 :(得分:-1)
由于JSON对象位于数组([]符号)内,因此您必须通过数组中的JSON索引来引用JSON对象。像这样。
const data = [{"date":1535624757,"date_ms":1535624757427,"amount":90.389717,"price":0.00860497,"type":"buy","tid":251916659},{"date":1535624757,"date_ms":1535624757428,"amount":99.428689,"price":0.00860497,"type":"buy","tid":251916662},{"date":1535624757,"date_ms":1535624757469,"amount":384.65968,"price":0.00860497,"type":"buy","tid":251916663}];
console.log(data[0]);
Here's some info在数组上是它们的索引。