我一直在从事一些项目,我必须处理以换行符分隔的JSON数据。这是数据的形状:
{"response": "True", "controllerId": "2751", "level": "INFO", "logType": "watchdogResponse", "deviceId": "2751", "container": "firmware", "epoch": "1549996256", "module": "hostServices", "ts": "2019-02-13 00:00:56"}
{"ts": "2019-02-13 00:01:10", "epoch": "1549996270", "level": "INFO", "module": "jr", "logType": "running", "controllerId": "2751", "deviceId": "2751", "rid": "EXTERNAL CALL", "val": "1549996260000"}
{"ts": "2019-02-13 00:01:10", "epoch": "1549996270", "level": "INFO", "module": "applicationMain", "logType": "wifi", "controllerId": "2751", "deviceId": "2751", "networkStrength": "100.0"}
现在如何解析它,我必须按其键对数据进行排序。
答案 0 :(得分:0)
您可以使用JSON.parse()
将JSON解析为javascript对象。要按字典顺序对数据进行排序,可以使用Object.entries()
创建一个数组,然后使用array's sort()
method对其进行排序。
let obj = JSON.parse(data)
let arr = Object.entries(obj).sort()
然后arr
将是一个数组,其中包含按其键排序的键值对(作为数组)。
答案 1 :(得分:0)
如果我理解正确,则数据不是有效的JSON字符串,而是由换行符分隔的JSON字符串。因此,这就是将data
转换为具有排序键顺序的对象数组的方式:
'use strict';
const data =
`{"response": "True", "controllerId": "2751", "level": "INFO", "logType": "watchdogResponse", "deviceId": "2751", "container": "firmware", "epoch": "1549996256", "module": "hostServices", "ts": "2019-02-13 00:00:56"}
{"ts": "2019-02-13 00:01:10", "epoch": "1549996270", "level": "INFO", "module": "jr", "logType": "running", "controllerId": "2751", "deviceId": "2751", "rid": "EXTERNAL CALL", "val": "1549996260000"}
{"ts": "2019-02-13 00:01:10", "epoch": "1549996270", "level": "INFO", "module": "applicationMain", "logType": "wifi", "controllerId": "2751", "deviceId": "2751", "networkStrength": "100.0"}`;
const sortedArrayOfObjects = data
.split('\n')
.map(JSON.parse)
.map(obj => Object.entries(obj).sort().reduce(
(o, [k, v]) => (o[k] = v, o), {})
);
console.log(sortedArrayOfObjects);
答案 2 :(得分:0)
假设您要使用日期进行排序。
let input = `{"response": "True", "controllerId": "2751", "level": "INFO", "logType": "watchdogResponse", "deviceId": "2751", "container": "firmware", "epoch": "1549996256", "module": "hostServices", "ts": "2019-02-13 00:00:56"}
{"ts": "2019-02-13 00:01:10", "epoch": "1549996270", "level": "INFO", "module": "jr", "logType": "running", "controllerId": "2751", "deviceId": "2751", "rid": "EXTERNAL CALL", "val": "1549996260000"}
{"ts": "2019-02-13 00:01:10", "epoch": "1549996270", "level": "INFO", "module": "applicationMain", "logType": "wifi", "controllerId": "2751", "deviceId": "2751", "networkStrength": "100.0"}`
let out = input.split('\n').map(JSON.parse).sort((a, b) => {
new Date(a.ts) > new Date(b.ts);
})
console.log(out);