我想将ndjson文件中的数据分配给一个js变量。我试着把它放在一个数组和一个对象中,但这会抛出错误。
我试过这样做...
var data = [{"attributes":{}}
{"attributes":{}}
{"attributes":{}}]和
var data = {{"attributes":{}}
{"attributes":{}}
{"attributes":{}}}但这是行不通的。
有没有人可以帮我把这个ndjson值赋值给一个js变量而不抛出错误。
发布于 2020-05-13 00:33:04
ndjson对于流值很有用-其格式本质上是一个对象数组,但(1)省略了最外面的括号[],以便隐含该数组,以及(2)记录之间的分隔符是换行符而不是逗号。基本上是一个行流,其中每行都是JSON格式的一条记录。The spec不清楚记录/行本身是否可以是数组,但对象可以包含数组。
使用规范中提供的the example,您一定以某种方式收到了此文本流:
{"some":"thing"}
{"foo":17,"bar":false,"quux":true}
{"may":{"include":"nested","objects":["and","arrays"]}}假设您已经收到了它,并将其存储在一个变量中,该变量应该是一个字符串input。然后,您可以使用input.split('\n')在换行处断开此字符串
通过JSON.parse(…)解析每一个,并将结果保存到一个数组中。
let input = '{"some":"thing"}\n{"foo":17,"bar":false,"quux":true}\n{"may":{"include":"nested","objects":["and","arrays"]}}';
let result = input.split('\n').map(s => JSON.parse(s));
console.log('The resulting array of items:');
console.log(result);
console.log('Each item at a time:');
for (o of result) {
console.log("item:", o);
}
发布于 2020-05-12 23:57:14
Javascript数组的对象会是这样的,请看他们之间的逗号,
var data = [{
"attributes": {}
},{
"attributes": {}
},{
"attributes": {}
}];
console.log(data);
对象内部的或对象可能是这样的,我猜你不想这样,
var data = {
"attributes": {},
"attributes": {},
"attributes": {}
};
console.log(data);
https://stackoverflow.com/questions/61756135
复制相似问题