186

How do you make JS think that a string is JSON ?

I have a function which only works if JSON object is passed to it. If I pass a string to it, with same format as JSON, it doesn't work. So I want to make that function think that the string passed to it is a JSON. The string is indeed in the JSON format.

I also tried the following. I inputted the string through Ajax , with "handle as" parameter as "JSON", and then when I passed the result to the function it works.

So I deduced the problem is not with the string. How do I convert this string to JSON? If i get same string through ajax request and then passing it to function works, whereas directly passing it doesn't work.

The string is as follows:

  {
     "data": [
   {
  "id": "id1",
      "fields": [
        {
          "id": "name1",
          "label": "joker",
          "unit": "year"
        },
         {"id": "name2", "label": "Quantity"},
    ],
      "rows": [    data here....

and closing braces..
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Zer0
  • 2,171
  • 3
  • 17
  • 18
  • 1
    possible duplicate of [Safely turning a JSON string into an object](http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – Manse Jun 11 '12 at 08:55
  • 4
    Your title is misleading. Based on the content of your question I'd rather say you want to convert a string containing JSON into a JavaScript object/array. – Felix Kling Jun 11 '12 at 09:04
  • OK i solved it. There was a \n in the string. Now only have to figure out how to use JSON.parse with this. – Zer0 Jun 12 '12 at 11:59
  • Ok i fixed it. Goto http://jsonlint.com/ and put your string there. If it says its correct, then you can use JSONParse to achieve the same. – Zer0 Jun 14 '12 at 05:34
  • In case anyone reads this, the title is supposed to be "converting a JSON string into an object" –  Dec 04 '19 at 09:27

10 Answers10

412
var obj = JSON.parse(string);

Where string is your json string.

Durandal
  • 5,575
  • 5
  • 35
  • 49
Kshitij
  • 8,474
  • 2
  • 26
  • 34
  • 1
    This is not working. It is throwing an error "SyntaxError: JSON.parse: unexpected character" . There is nothing wrong with the string as when i get the same string through a ajax request and handle it as "JSON", no problem occurs. – Zer0 Jun 11 '12 at 09:00
  • please post your acutal JSON string – Kshitij Jun 11 '12 at 09:11
  • { "data": [ { id": - you are missing a double quote here, i.e. starting double quote of id – Kshitij Jun 11 '12 at 09:23
  • I have no idea why SO removed it. Its present in the string. it is { "data": [ { "id" – Zer0 Jun 11 '12 at 09:24
  • 2
    When I get it through Ajax it works as then it handles the response as JSON . So I think I have to convert this to a JSON object.. – Zer0 Jun 11 '12 at 09:25
  • even now the extra comma after '"Quantity"}, ' looks suspicious. You need to share your entire json string for us to know. JSON.parse() is a standard approach and should work for all valid json strings. – Kshitij Jun 11 '12 at 09:31
  • 2
    I ended up going to jsonlint.com, and making sure my Json is right – Zer0 Feb 25 '14 at 09:18
27

You can use the JSON.parse() for that.

See docs at MDN

Example:

var myObj = JSON.parse('{"p": 5}');
console.log(myObj);
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 1
    This is not working. It is throwing an error "SyntaxError: JSON.parse: unexpected character" . There is nothing wrong with the string as when i get the same string through a ajax request and handle it as "JSON", no problem occurs. – Zer0 Jun 11 '12 at 09:01
  • 2
    @Zer0: You should update your question with how you are trying it along with your json string. – Sarfraz Jun 11 '12 at 09:02
  • 5
    @Zer0: We can only answer to the best of our knowledge. You say you have a JSON string, we answer accordingly. It seems your string is different, if you'd post it, we can answer taking this into account. If you ask a question about coding, then code/data is indispensable . – Felix Kling Jun 11 '12 at 09:07
7

I had the same problem with a similar string like yours

{id:1,field1:"someField"},{id:2,field1:"someOtherField"}

The problem here is the structure of the string. The json parser wasn't recognizing that it needs to create 2 objects in this case. So what I did is kind of silly, I just re-structured my string and added the [] with this the parser recognized

var myString = {id:1,field1:"someField"},{id:2,field1:"someOtherField"}
myString = '[' + myString +']'
var json = $.parseJSON(myString)

Hope it helps,

If anyone has a more elegant approach please share.

Dave Anderson
  • 11,836
  • 3
  • 58
  • 79
Abraham
  • 79
  • 1
  • 2
  • In your code above, you've constructed `myString` incorrectly. It's not a string, and it's incorrectly formatted JSON. Your second line would then become redundant. Here's what it should be: `var myString = '[{"id":1,"field1":"someField"},{"id":2,"field1":"someOtherField"}]'` I know this is quite an old post, but I thought I'd add some clarity in case anyone finds it. – James Eberhardt Oct 29 '17 at 12:05
  • I solved my issue using `$.parseJSON` where `JSON.parse` was not working and throwing an error *`JSON.parse is not a function`* – brasofilo Mar 22 '18 at 15:28
5
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

link:-

http://api.jquery.com/jQuery.parseJSON/

sandeep patel
  • 436
  • 4
  • 16
4

Simply use eval function.

var myJson = eval(theJsibStr);
Siyavash Hamdi
  • 2,764
  • 2
  • 21
  • 32
4

convert the string to HashMap using Object Mapper ...

new ObjectMapper().readValue(string, Map.class);

Internally Map will behave as JSON Object

Sugan V
  • 89
  • 2
  • 6
2
var Data=[{"id": "name2", "label": "Quantity"}]

Pass the string variable into Json parse :

Objdata= Json.parse(Data);
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
Ankita_Shrivastava
  • 1,225
  • 11
  • 9
  • In your example, `Data` is already an object, so there would be no need to parse it. You would need some quotes surrounding all your Data in order to make it a string. – James Eberhardt Oct 29 '17 at 12:09
2

Let's us consider you have string like

example : "name:lucy,age:21,gender:female"

function getJsonData(query){
    let arrayOfKeyValues = query.split(',');
    let modifiedArray =  new Array();
    console.log(arrayOfKeyValues);
    for(let i=0;i< arrayOfKeyValues.length;i++){
        let arrayValues = arrayOfKeyValues[i].split(':');
        let arrayString ='"'+arrayValues[0]+'"'+':'+'"'+arrayValues[1]+'"';
        modifiedArray.push(arrayString);
    }
    let jsonDataString = '{'+modifiedArray.toString()+'}';
    let jsonData = JSON.parse(jsonDataString);
    console.log(jsonData);
    console.log(typeof jsonData);
    return jsonData;
}

let query = "name:lucy,age:21,gender:female";
let response = getJsonData(query);
console.log(response);

`

Shishir
  • 327
  • 3
  • 6
1

JSON.parse() function will do.

or

Using Jquery,

var obj = jQuery.parseJSON( '{ "name": "Vinod" }' );
alert( obj.name === "Vinod" );
Prasad Khode
  • 6,602
  • 11
  • 44
  • 59
Vinod Selvin
  • 369
  • 2
  • 10
1

JSON.parse() is your friend. Here's an example:

let obj = JSON.parse(yourString)
console.log(typeof obj); // prints 'object' assuming your string is correctly formatted
ridwan rf
  • 91
  • 3