0

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!

ItzHex
  • 90
  • 9
  • 4
    What messed-up API returns data like this - and not _proper_ JSON? You will probably have to write your own parser for this, if this can't get fixed on the API side. – CBroe Feb 06 '23 at 13:45

1 Answers1

1

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:

// ⚠️ 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);

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.

jsejcksn
  • 27,667
  • 4
  • 38
  • 62