【问题标题】:Parse string in nodejs to an array将nodejs中的字符串解析为数组
【发布时间】:2020-09-20 19:07:37
【问题描述】:

如何在nodejs中将后面的字符串转换成数组?

"Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]"

我尝试了 JSON.parse,但出现错误:位置 2 处 JSON 中的意外标记 c

你有什么想法吗?

【问题讨论】:

  • 先删除Content: ? string.replace("Content: ", "")
  • 它不是有效的 JSON,所以 JSON.parse 不起作用。
  • @JeremyThille——这不足以使其有效,属性名称也必须用双引号括起来(假设所有值都是类型号)。
  • 同意,这两项更改都需要到位,JSON.parse 才能正常工作。 @VaadinDestroyer 我假设您无法更改原始格式,并且仍在寻找解析方法?
  • 如果是这样,首先在 "Content:" 上运行 string.replace,然后使用 this answer 等方法添加引号(注意这是 Java,而不是 JS)。

标签: javascript arrays node.js string


【解决方案1】:

给定的字符串不是 JSON 字符串,因此请尝试关注 replace 并将键作为字符串。

y =
  "Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]";

y = `{${y}}`;
y = y.replace("},]", "}]");
y = y.replace(/Content/g, '"Content"');
y = y.replace(/id/g, '"id"');
y = y.replace(/value/g, '"value"');
y = y.replace(/number/g, '"number"');


str = JSON.parse(y);

console.log(str);

【讨论】:

    【解决方案2】:

    您首先需要删除“Content:”,然后您需要使字符串符合 json 标准,就像这样。

    const a = '[{"id": 1, "value": 1, "number": 1}]'
    

    【讨论】:

      【解决方案3】:
      const str = "Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]".substring(8);
      

      这是解决问题“位置 2 处 JSON 中的意外标记 c。”。 而且您已经不需要 JSON.parse

      【讨论】:

        【解决方案4】:

        我知道人们不喜欢使用eval(),但是对于做一些事情是有用的。

        检查一下:

        var string = "Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]";
        var array = eval(string);
        
        console.log(array);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-02-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-12
          • 2012-10-14
          • 2017-04-04
          • 2014-03-04
          相关资源
          最近更新 更多