【问题标题】:parse array in string form in javascript在javascript中以字符串形式解析数组
【发布时间】:2020-06-16 14:43:53
【问题描述】:

我正在尝试处理来自 3rd 方 api 的 json 文档。数据返回是字符串格式,类似这样:

{
   "response":{
      "field1":7,
      "field2":0,
      "records":[
         {
            "id":"1",
            "title":[
               "cyx"
            ],
            "doc1":[
               "1",
               "2"
            ],
            "doc2":["\n\t        [\n\t        \t\"1\",\n\t            \"2\",\n\t        ]\n\t    "],
         }
      ]
   }
}

当我尝试处理 doc2 时,它会返回如下字符串:[ "1", "2", ],而不是像在 doc1 的演示中那样返回一个数组。 当我尝试使用 JSON.parse() 时,应用程序会引发错误。

这是一个简单的问题演示: https://jsfiddle.net/harpalshergill/39acf4dn/24/

我想知道如何在不手动删除空格、\n、\t 字符的情况下解析这个数组? 谢谢你的帮助。

【问题讨论】:

  • 代码中没有doc1。能否请您添加此字段。
  • 问题是尾随, 导致JSON.parse 抛出错误。如图所示,doc2 值不是有效的 JSON。如果这是真实数据,则生成错误。
  • @crashmstr 你是对的。如果 doc2 中没有“,”,则 JSON.parse 有效

标签: javascript json reactjs string-parsing


【解决方案1】:

您可以像示例中那样替换字符

var body = " {\"Warranty\": [ \n { \n \"Name\": \"test\", \n \"Type\": \"test2\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"Test6\", \n \"Type\": \"test7\", \n \"Months\": \"6\", \n }, \n { \n \"Name\": \"test9\", \n \"Type\": \"test10\", \n \"Miles\": \"10000\", \n } \n ]} ".replace(/\r?\n|\r/g, "").replace(/\s+/g, "").replace(/,}/g,'}');
var object = JSON.parse(body);

【讨论】:

    【解决方案2】:

    您可以使用以下方法:

    const doc2 = ["\n\t        [\n\t        \t\"1\",\n\t            \"2\",\n\t        ]\n\t    "];
    const result = doc2.toString().replace(/[^\w\r\n]+/gm, "").trim().split('\n');
    
    
    // result =  ["1", "2"]
    
    

    工作示例:https://jsfiddle.net/2kyp6aow/

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 2021-05-08
      • 1970-01-01
      • 2013-04-27
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多