英文:
How can I convert a string containing an array of javascript objects, into an array of javascript objects?
问题
我有一个包含 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 返回的,所以我不能直接将它写成 JavaScript 对象数组。希望能得到帮助,谢谢!
英文:
I've got a string containing an array of JavaScript objects which looks something like this:
{ 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' },
It's being returned from an API, so I can't just write it out as an array of js objects in the first place.
Any help would be much appreciated, thanks!
答案1
得分: 1
The best way to fix it is to modify the API to respond with properly formatted JSON.
If neither of those are an option, you might try using an AST parser.
As a very last resort, writing your own parser is always a possibility.
英文:
The best way to fix it is to modify the API to respond with properly formatted JSON.
Failing that possibility, you might be able to get by with using eval
in a sandboxed environment, using syntax similar to this:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// ⚠️ 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);
<!-- end snippet -->
If neither of those are an option, you might try using an AST parser. See more at the question What is JavaScript AST, how to play with it?
As a very last resort, writing your own parser is always a possibility.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论