[javascript] Converting a string to JSON object

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..

This question is related to javascript ajax json

The answer is


convert the string to HashMap using Object Mapper ...

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

Internally Map will behave as JSON Object


Let's us consider you have string like

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

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

`


var Data=[{"id": "name2", "label": "Quantity"}]

Pass the string variable into Json parse :

Objdata= Json.parse(Data);

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

link:-

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


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

See docs at MDN

Example:

var myObj = JSON.parse('{"p": 5}');
console.log(myObj);

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.


JSON.parse() function will do.

or

Using Jquery,

var obj = jQuery.parseJSON( '{ "name": "Vinod" }' );
alert( obj.name === "Vinod" );

Simply use eval function.

var myJson = eval(theJsibStr);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?