[英]Split new-line JSON into one array
我有一个来自 web 服务器的 JSON,如下所示:
{"timestamp":1642069251.6908009,"station_id":"ORBB","channel":5,"freq":131.725,"level":-28.1,"error":0,"mode":"2","label":"Q0","block_id":"8","ack":false,"tail":"A6-ANR","flight":"G90369","msgno":"S10A"}
{"timestamp":1642069257.00876,"station_id":"ORBB","channel":5,"freq":131.725,"level":-41.3,"error":0,"mode":"2","label":"Q0","block_id":"7","ack":false,"tail":"PH-HXO","flight":"HV6905","msgno":"S28A"}
{"timestamp":1642069259.057013,"station_id":"ORBB","channel":5,"freq":131.725,"level":-24.9,"error":0,"mode":"D","label":"Q0","block_id":"9","ack":false,"tail":"A6-ANR","flight":"G90369","msgno":"S11A"}
我已经遵循了这个答案,但我没有在控制台中显示任何内容。
l 无法编辑上面的数据 JSON 以提供有效的 JSON,因为它来自使用 Ajax 的数据服务器。
$(document).ready(() => {
$.ajax('acarsdec.json', {
type: 'GET',
//dataType: "text",
timeout: 10000,
cache: false,
}).done(function (data, textStatus, jqXHR) {
const dataasfile = `data:text/plain;base64,${btoa(data)}`;
fetch(dataasfile).then(res => res.text()).then(text => {
let jsonstr = `[${text.split('\n').join(',')}]`;
let json = JSON.parse(jsonstr);
console.log(json);
});
})
})
作为起点,您显示的代码段无效 JSON,因此没有理由尝试将其解析为 JSON。
如果您可以相信来源是“伪”JSON,每行一个 object,您可以在新行 (\n) 上拆分文本,然后用逗号 (,) 再次加入字符串,然后在字符串周围加上方括号:
let jsonstr = `[${text.split('\n').join(',')}]`;
在这里,我使用 fetch function 和数据 URL 来模拟 AJAX 请求。
/***** start setup for demostration *****/ const data = `{"timestamp":1642069251.6908009,"station_id":"ORBB","channel":5,"freq":131.725,"level":-28.1,"error":0,"mode":"2","label":"Q0","block_id":"8","ack":false,"tail":"A6-ANR","flight":"G90369","msgno":"S10A"} {"timestamp":1642069257.00876,"station_id":"ORBB","channel":5,"freq":131.725,"level":-41.3,"error":0,"mode":"2","label":"Q0","block_id":"7","ack":false,"tail":"PH-HXO","flight":"HV6905","msgno":"S28A"} {"timestamp":1642069259.057013,"station_id":"ORBB","channel":5,"freq":131.725,"level":-24.9,"error":0,"mode":"D","label":"Q0","block_id":"9","ack":false,"tail":"A6-ANR","flight":"G90369","msgno":"S11A"}`; const dataasfile = `data:text/plain;base64,${btoa(data)}`; /***** end setup for demostration *****/ /* replace dataasfile with your URL to the API */ fetch(dataasfile).then(res => res.text()).then(text => { let jsonstr = `[${text.split('\n').join(',')}]`; let json = JSON.parse(jsonstr); console.log(json); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.