在JavaScript中将无效的JSON对象转换为有效的JSON对象

时间:2016-12-02 07:16:39

标签: javascript arrays json node.js validation

我知道这已经被问到了问题,但我没有得到之前提出的任何问题的答案......

我的问题是 - 服务器发送一个JSON对象数组作为字符串,我想将字符串转换为有效的JSON数组。

示例:服务器像这样发送

 '{
    "ts": "3170075",
    "eventid": 25,
    "oper_minutes": 48577,
    "time": "2016-12-02T06:36:36Z",
    "lto": "7200000",
    "package_name": "XXX",
    "timestamp": "1480660593188",
    "action_type": "1",
    "events": [{
        "device_name": 0,
        "key_category": 1,
        "eventid": 15,
        "ts": "2111"
     }, {
        "power_state": 3,
        "reason": 1,
        "eventid": 1,
        "ts": "2113"
     }]
}, {
    "ts": "3170084",
    "eventid": 25,
    "oper_minutes": 48577,
    "time": "2016-12-02T06:36:36Z",
    "lto": "7200000",
    "package_name": "XXXX",
    "timestamp": "1480660593218",
    "action_type": "1",
    "events": [{
        "device_name": 0,
        "key_category": 1,
        "eventid": 15,
        "ts": "2111"
     }, {
        "power_state": 3,
        "reason": 1,
        "eventid": 1,
        "ts": "2113"
     }]
}'

我想使用纯javascript将它转换为两个对象的有效数组。

示例:

   [{
    "ts": "3170075",
    "eventid": 25,
    "oper_minutes": 48577,
    "time": "2016-12-02T06:36:36Z",
    "lto": "7200000",
    "package_name": "XXX",
    "timestamp": "1480660593188",
    "action_type": "1",
    "events": [{
        "device_name": 0,
        "key_category": 1,
        "eventid": 15,
        "ts": "2111"
     }, {
        "power_state": 3,
        "reason": 1,
        "eventid": 1,
        "ts": "2113"
     }]
}, {
    "ts": "3170084",
    "eventid": 25,
    "oper_minutes": 48577,
    "time": "2016-12-02T06:36:36Z",
    "lto": "7200000",
    "package_name": "XXX",
    "timestamp": "1480660593218",
    "action_type": "1",
    "events": [{
        "device_name": 0,
        "key_category": 1,
        "eventid": 15,
        "ts": "2111"
     }, {
        "power_state": 3,
        "reason": 1,
        "eventid": 1,
        "ts": "2113"
     }]
}]

我已经尝试过JSON.parse,JSON.stringify等

没有预期的有效结果..

注意:此对象数组可以是任意大小,服务器有时会发送1000个对象,有时只发送10个但作为字符串。不应该花太多时间来处理。

请帮助,我已经坚持了将近一天..我在nodeJS中使用它,所以只使用纯javaScript或NPM库。

1 个答案:

答案 0 :(得分:1)

您发送的JSON字符串无效,因为它应该封装在[]。

你可以这样做:

var str = '{"ts": "3170075","eventid": 25,"oper_minutes": 48577,"time": "2016-12-02T06:36:36Z","lto": "7200000","package_name": "XXX","timestamp": "1480660593188","action_type": "1","events": [{"device_name": 0,"key_category": 1,"eventid": 15,"ts": "2111" }, {"power_state": 3,"reason": 1,"eventid": 1,"ts": "2113" }]}, {"ts": "3170084","eventid": 25,"oper_minutes": 48577,"time": "2016-12-02T06:36:36Z","lto": "7200000","package_name": "XXXX","timestamp": "1480660593218","action_type": "1","events": [{"device_name": 0,"key_category": 1,"eventid": 15,"ts": "2111" }, {"power_state": 3,"reason": 1,"eventid": 1,"ts": "2113"}]}';

    var obj = JSON.parse(`[${str}]`);

您尝试手动执行此操作的错误是因为您的帖子中发布的原始字符串无效(因为换行符)。