如何将包含javascript对象数组的字符串转换为javascript对象数组?

mrphzbgm  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(180)

我得到了一个包含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对象数组。任何帮助都将不胜感激,谢谢!

11dmarpk

11dmarpk1#

解决此问题的最佳方法是修改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解析器。
作为最后的手段,编写自己的解析器始终是一种可能性。

相关问题