user3386236
user3386236

Reputation: 13

How to convert a string to an array of dicts

I want to convert a string in this format:

'[{"param":"MDN","required":"true"},{"param":"Attribute","required":"false"}]'

to an array of dicts, such that I can easily parse through them.

I have tried using regex and such, but I am not able to figure it out.

contents = contents.substring(1, contents.length-1);
var variables = contents.split(",");

I tried to remove the first and last character of the string, the square brackets and then split with commas, but the problem is that the dictionaries inside them have commas.

The final result should be:

[{"param":"MDN","required":"true"},{"param":"Attribute","required":"false"}]

Same as input, but not a string anymore.

Upvotes: 0

Views: 91

Answers (1)

msanford
msanford

Reputation: 12227

Do you mean just JSON.parse()?

const parsed = JSON.parse('[{"param":"MDN","required":"true"},{"param":"Attribute","required":"false"}]')

console.dir(parsed)

Upvotes: 2

Related Questions