【问题标题】:How can I convert a string containing an array of javascript objects, into an array of javascript objects?如何将包含 javascript 对象数组的字符串转换为 javascript 对象数组?
【发布时间】:2023-02-06 22:30:32
【问题描述】:

我有一个包含 JavaScript 对象数组的字符串,它看起来像这样:

{ name: 'Taco Salad', description: 'A dish made with lettuce, tomatoes, cheese, and seasoned ground beef or chicken, all served in a tortilla bowl.', nationality: 'Mexican', id: '1' },  { name: 'Fried Rice', description: 'A stir-fried rice dish with eggs, vegetables, and meat or seafood.', nationality: 'Chinese', id: '2' }, { name: 'Spaghetti Bolognese', description: 'An Italian dish of minced beef or pork in a tomato sauce, served with spaghetti.', nationality: 'Italian', id: '3' },

它是从一个 API 返回的,所以我不能一开始就把它写成一个 js 对象数组。 任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 什么乱七八糟的 API 返回这样的数据 - 而不是恰当的JSON?如果无法在 API 端解决这个问题,您可能必须为此编写自己的解析器。

标签: javascript arrays object


【解决方案1】:

修复它的最佳方法是修改 API 以使用格式正确的 JSON 进行响应。


如果没有这种可能性,您可以在沙盒环境中使用 eval,使用类似于以下的语法:

// ⚠️ DANGER: Don't do this in your host environment!

const input = `{ name: 'Taco Salad', description: 'A dish made with lettuce, tomatoes, cheese, and seasoned ground beef or chicken, all served in a tortilla bowl.', nationality: 'Mexican', id: '1' },  { name: 'Fried Rice', description: 'A stir-fried rice dish with eggs, vegetables, and meat or seafood.', nationality: 'Chinese', id: '2' }, { name: 'Spaghetti Bolognese', description: 'An Italian dish of minced beef or pork in a tomato sauce, served with spaghetti.', nationality: 'Italian', id: '3' },`;

const array = eval(`[${input}]`);
const json = JSON.stringify(array);

// send the sanitized json back to the host somehow...
console.log(json);

如果这些都不是一个选项,您可以尝试使用 AST 解析器。查看更多问题What is JavaScript AST, how to play with it?


作为最后的手段,编写自己的解析器始终是一种可能。

【讨论】:

    【解决方案2】:

    仅对于转换,我会在您的响应两侧创建一个带有方括号字符串的变量,如下所示:

    let response = "[" + original_response + "]"
    response = JSON.parse(response)
    

    【讨论】:

      【解决方案3】:

      let str = "{ name: 'Taco Salad', description: 'A dish made with lettuce, tomatoes, cheese, and seasoned ground beef or chicken, all served in a tortilla bowl.', nationality: 'Mexican', id: '1' },  { name: 'Fried Rice', description: 'A stir-fried rice dish with eggs, vegetables, and meat or seafood.', nationality: 'Chinese', id: '2' }, { name: 'Spaghetti Bolognese', description: 'An Italian dish of minced beef or pork in a tomato sauce, served with spaghetti.', nationality: 'Italian', id: '3' }"
      const result = str.replace(/},/g, "}},").split("},").map((ele, ind)=> {
        eval(`var obj=`+ele)
        return obj;
      })
      
      console.log(result)

      【讨论】:

      • 如果你想要更结构化的结果,你可以像我的代码一样尝试。
      猜你喜欢
      • 1970-01-01
      • 2017-08-24
      • 2013-04-19
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      • 2016-10-09
      相关资源
      最近更新 更多