0

I'm using JavaScript and I want to convert string type value like this:

'[{"key": "a", "value": "aa"}, {"key": "b", "value": "bb"}]'

to array type, without '' quotes, like this:

[{"key": "a", "value": "aa"}, {"key": "b", "value": "bb"}].

I receive this type as an argument to a function where I have to treat the value as Array. But currently I can't push or pop items because the value is of string type.

abdul-wahab
  • 2,182
  • 3
  • 21
  • 35
Jung Chun
  • 5
  • 6
  • @user4642212 Yes it was right. But I didn't know that my example was a JSON string so I couldn't find this post at google. Thanks anyway! – Jung Chun Jul 20 '20 at 05:13

3 Answers3

1

You can use JSON.parse() to parse it into a javascript object

Mausom Saikia
  • 150
  • 1
  • 9
0

Assuming the string provided is a valid json array string(but it's not. I'd to fix a missing quote after value field). However you cannot do array operations in that until you convert it into a valid javascript array.

var jsonString='[{"key": "a", "value": "aa"}, {"key": "b", "value": "bb"}]';
var array=JSON.parse(jsonString);
array.push({key:'c',value:'cc'});
Beingnin
  • 2,288
  • 1
  • 21
  • 37
0

We can parse the data with JSON.parse(), and the data becomes a JavaScript object. Make sure the text is written in JSON format, or else you will get a syntax error.

When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.

Example:

var string = '[{"key": "a", "value": "aa"}, {"key": "b", "value": "bb"}]';
var arr = JSON.parse(string)

In this case in "arr" variable we will be getting 2 objects in array

Haris George
  • 291
  • 5
  • 16
  • You should use proper markup to make your answer more distinguishable from code parts and explanation parts. – Robert Mennell Jul 20 '20 at 05:02
  • @RobertMennell thanks for your feedback. I have just answered 2 or 3 questions in stack overflow. Wasn't so good in explaining part though. I have edited my answer in the best way I can. Not sure if there is any more needed. If you don't mind can you please let me know if there are any more changes needed ? – Haris George Jul 20 '20 at 05:41
  • https://stackoverflow.com/editing-help this should point you in the right direction for doing some code example in MarkDown so that your bolds are instead treated as code or are preformatted. Right now it just looked like text, not a code example. – Robert Mennell Jul 20 '20 at 06:06
  • 1
    @RobertMennell Thanks. I think now the answer looks better. Right? – Haris George Jul 20 '20 at 06:15