Sriya
Sriya

Reputation: 187

Parse JSON array from string

I want to convert the following string to an array

var string = '["YES","NO"]';

How do I do this?

Upvotes: 12

Views: 15998

Answers (3)

Tomgrohl
Tomgrohl

Reputation: 1767

You can also use $.parseJSON:

var string = '["YES","NO"]';
var array = $.parseJSON(string);

Upvotes: 0

t3dodson
t3dodson

Reputation: 4007

use the global JSON.parse method

JSON.parse('["YES","NO"]'); // returns ["YES", "NO"]

You can also use the JSON.stringify method to write the array back to a string if thats how you are storing it.

JSON.stringify(["YES", "NO"]); // returns '["YES", "NO"]'

Upvotes: 15

Thibault Bach
Thibault Bach

Reputation: 556

var str= '["YES","NO"]';
var replace= str.replace(/[\[\]]/g,'');
var array = replace.split(',');

Fiddle : http://jsfiddle.net/9amstq41/

Upvotes: 4

Related Questions