Converting a string to JSON object - javascript

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

var obj = JSON.parse(string);
Where string is your json string.

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.

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
link:-
http://api.jquery.com/jQuery.parseJSON/

Simply use eval function.
var myJson = eval(theJsibStr);

convert the string to HashMap using Object Mapper ...
new ObjectMapper().readValue(string, Map.class);
Internally Map will behave as JSON Object

var Data=[{"id": "name2", "label": "Quantity"}]
Pass the string variable into Json parse :
Objdata= Json.parse(Data);

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);
`

JSON.parse() function will do.
or
Using Jquery,
var obj = jQuery.parseJSON( '{ "name": "Vinod" }' );
alert( obj.name === "Vinod" );

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

Related

Coverting object into string

I have one doubt in stringify an object.
In input is below:
var obj = [{'name' : 'Jenisha', 'lastName' : 'dalin'}];
obj.__used = true;
My expected output:
JSON.stringify(obj, undefined, 4);
"[
{
"name": "Jenisha",
"lastName": "dalin"
}
],
"__used" : true
"
But the results are:
JSON.stringify(obj, undefined, 4);
"[
{
"name": "Jenisha",
"lastName": "dalin"
}
]"
"__used" param removed. is any alternate function available to stringify an object.
Thanks in advance
Since you are essentially stringifying an array, a string key inside a JSON array representation makes no sense. This is also stated in the JSON.stringify documentation on MDN.
Since an array is stringified like this: ["value1", "value2"], and the keys are actually just numbers (0, 1, 2) and are left out, a string key as you added it is just ignored, because it cannot be represented in the output.
You can add both properties to an object and serialize this instead:
JSON.stringify ({
arr: [{'name' : 'Jenisha', 'lastName' : 'dalin'}],
used: true
});
JSON.stringify works with valid JSON format. but seems your Obj has invalid JSON format.
To verify your JSON goto: http://jsonlint.com/
Do not use [] in your code.
var obj = {'name' : 'Jenisha', 'lastName' : 'dalin'};
obj.__used = true;
Now if you stringify obj, you will get __used property as well.
Json was prepared by library from my side im just stringify that, while stringify the json the my object was getting removed. can we able over come this issue.
var obj = {'name' : 'Jenisha', 'lastName' : 'dalin'};
obj.__used = true;
This is how my json getting prepared

Fetch key inside a json object in php jquery

I am returning a json data to jquery using php. what i want is to access the keys inside the json. i followed a tutorial and used json stringify but im not able to access the keys.
json data :
[
{"id":"1","movie_name":"spiderman","releases_on":"20th August 2018"},
{"id":"2","movie_name":"batman","releases_on":"21st August 2018"},
{"id":"3","movie_name":"fast and furious 6","releases_on":"22nd August 2018"}
]
code in jquery:
var json = data;
var obj = JSON.stringify(json);
console.log(obj[1].id);
you have to use JSON.parse(json).
then, you can do it.
JSON.stringify() will take your JSON object and convert it to a JSON string (here which is response).
JSON.parse() will take stringified JSON and convert it to object so that you can access via . operator
for example,
var a = { name: "John", age: 20 }
console.log(typeof a) // object
var out = JSON.stringify(a)
console.log(typeof out) // string
var res = JSON.parse(out)
console.log(typeof res) // object
I hope you got it....

Unable to access a key value from a json

I have a json as below
var object = {200x200: "url1", 400x400: "url2", 800x800: "url3"};
I stringified the object and tried to acccess "200x200". But its throwing
undefined
object = JSON.stringify(object);
//object = {"200x200": "url1", "400x400": "url2", "800x800": "url3"};
I tried to access like this
object['200x200'] // got undefined
Any other way to access the url1 from this object ?
Because you json object is wrong format:
Wrap your keys in quotes, like this: https://codepen.io/creativedev/pen/LrBOmG
var object = {'200x200': "url1",'400x400': "url2", '800x800': "url3"};
Then check:
console.log(object['200x200']);
you will get output
Once you stringify it, it’s a string. You have to parse it back into an object.
var newObject = JSON.parse(object);
console.log(object[200x200];
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
you should change you object to
var object = {'200x200': "url1", '400x400': "url2", '800x800': "url3"};
object['200x200'] // 'url1'
You can parse it:
object = JSON.parse(object);
then access the key:
let url1 = object['200x200']
No idea why you would stringify it in the first place though!
let jsonObject = JSON.stringify(object);
// instead of:
let url1 = JSON.parse(JSON.stringify(object))['200x200']

Why I can't parse JSON in JavaScript?

JSON contains one object:
results[0] = { 'MAX(id)': 1 }
And this code doesn't work:
var text = results[0];
var obj = JSON.parse(text);
console.log(obj.MAX(id));
results[0] is already an object type
You can parse only from string to object like this:
JSON.parse('{ "MAX(id)": 1 }');
Your object is already a JSON. You don't need to parse it.
To access MAX(id) property, you can use [] notation as follows:
results[0] = { 'MAX(id)': 1 };
console.log(results[0]['MAX(id)']);
Your result[0] is a real javascript object. JSON.parse transforms text into objects, so you can't parse other objects with it.
var results = { 'MAX(id)': 1 };
//var text = results;
//var obj = JSON.parse(text);
alert(results['MAX(id)']);

Passing a external variable in JSON.parse function

I am trying to get a value from json by using the JSON.parse function. My json response is given below:
{
"rows": 10,
"os": "0",
"page": "1",
"total": "122",
"projects": {
"P143841": {
"id": "P143841",
"locations": [{
"geoLocId": "0002220957",
"latitude": "3.866667",
"longitude": "11.516667"
}],
}
}
}
I am able to get the value 10 if I do JSON.parse(obj.rows) but if I assign the rows to a variable say var value = rows and then I pass it to the JSON.parse(obj.value) function I got undefined.
P.S. I won't be knowing the names of the response parameters, i.e. i won't know if it will be rows or os quoting from the above example. I will be retrieving them from a database. If I perform the code below:
for (var i=0;i<length;i++) {
var value = responseParam_array[i];
console.log(obj.value);
}
I get the output but any help will be much appreciated.
As per the other answers you shouldn't need to parse individual properties, just parse the original JSON and then operate on the resulting object.
But as for this problem:
"if I assign the rows to a variable say var value = rows and then I pass it to the JSON.parse(obj.value) function I got undefined"
If value is a variable holding the name of a property of obj then you need:
obj[value]
// NOT
obj.value
When you use "dot" notation the part on the right of the dot is taken as the literal name of the property, not as a variable. Using the square-bracket syntax the expression in the brackets is evaluated and its result is taken as the property name.
you should be json-parsing your whole object and using the parsed object afterwards (you dont need to parse every property for itself)
var strObj = '{"rows": 10,"os": "0","page": "1","total": "122","projects":{"P143841":{"id":"P143841",}}';
var obj = JSON.parse(strObj);
var rows = obj.rows;
If I understand your question:
var str = '{ "some": "JSON String like the one above with", "rows": 10 }';
var parsed = JSON.parse(str);
var whatYouWant = parsed.rows;

Categories