[英]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.