【问题标题】:Javascript parse JSON with stringify neested objectJavascript 使用字符串化嵌套对象解析 JSON
【发布时间】:2020-10-09 22:58:32
【问题描述】:

我正在尝试解析应用程序 (AWS lambda) 在日志文件中写入的 json 对象,但该 json 嵌套了一个字符串化对象。类似的东西:

input = '{"object":"{\"base\":\"brn\",\"scope\":\"all\",\"channel\":\"sve\",\"service\":\"getAssociatesCards\",\"entity\":\"consolidate\",\"attribute\":\"cRelId\",\"qualifier\":\"45430608\"}"}'

当我尝试解析时失败:

JSON.parse(input)

出现此错误:

SyntaxError: Unexpected token b in JSON at position 13

我可以做些什么来解决这个问题并获得一个不错的 Json 对象?

【问题讨论】:

    标签: javascript json parsing nested


    【解决方案1】:

    如果您可以像问题中的代码一样控制 JSON 的定义,请使用 String.raw 声明它,以便将反斜杠解释为文字反斜杠。

    内部 object 属性包含更多 JSON,因此您也可以根据需要对其进行解析:

    const input = String.raw`{"object":"{\"base\":\"brn\",\"scope\":\"all\",\"channel\":\"sve\",\"service\":\"getAssociatesCards\",\"entity\":\"consolidate\",\"attribute\":\"cRelId\",\"qualifier\":\"45430608\"}"}`;
    const parsed = JSON.parse(input);
    console.log(JSON.parse(parsed.object));

    【讨论】:

    • 嗨,我无法控制 JSON 的定义。我从一个文件中读取了 JSON,我正在尝试解析它。
    【解决方案2】:

    如果您从某个日志文件中读取它并且您无法控制它是如何定义的,您总是可以剥离内部 json 并自行解析它。

    var input = '{"object":"{\"base\":\"brn\",\"scope\":\"all\",\"channel\":\"sve\",\"service\":\"getAssociatesCards\",\"entity\":\"consolidate\",\"attribute\":\"cRelId\",\"qualifier\":\"45430608\"}"}';
    
    var innerJSON = input.substring(11, input.length - 2);
    
    console.log({
      object: JSON.parse(innerJSON)
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-08
      • 2011-11-27
      • 2015-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多