Coverting object into string - javascript

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

Related

Convert Object to JSON Object

I am using DataTables library and I have hard times in receiving data in a proper format so I am trying to adjust it before DataTable library tries to fetch data into table. I have an ajax call which returns an object of the following format:
data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]
And my desired output is: data:[ [{ "SomeKey":"SomeValue" } , { ...} ],[...] ]
I have tried JSON.stringify or eval method , but did not worked , also tried those 2 methods when return type was some sort of string but then it inserts \ before " so It does not convert to json. Any help or good tracks would be appreciated.
This has nothing to do with JSON. :-)
data is apparently an array of arrays of objects, where each object has properties valled Key and Value.
If you want to create a new array of arrays of objects, where the objects have a property named by the Key value whose value is the Value value, you can do that like this:
data = data.map(a => a.map(({Key,Value}) => ({[Key]: Value})));
That uses map on the arrays (both the outer and inner ones) and destructuring to pick out the Key and Value properties from each object in the subarrays, and uses computed property names to set the property name on the new object.
In ES5 and earlier, that would look like this:
data = data.map(function(a) {
return a.map(function(obj) {
var newObj = {};
newObj[obj.Key] = obj.Value;
return newObj;
});
});
You should look into Array.prototype.map (mdn)
let data = [[{Key: "SomeKey", Value: "SomeValue"}]];
let output = data.map(a => a.map(({Key, Value}) => ({[Key]: Value})));
console.log(output);
Note the [Key] syntax. To put it simply, whereas var x = 'key'; y = {x: 3} will assign the object {x: 3}, x = 'key'; y = {[x]: 3} will assign the object {key: 3}.
If you're receiving literally the string "data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]", then you may trim the first 5 characters ('data:') and then use JSON.parse.

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

convert a JavaScript string to a Javascript object. Using JSON class does not work [duplicate]

I am trying to parse a string into an object.
I have looked at the jQueryparseJSON documentation at the following link
I've also included the jquery library so I know it's not that.
This is my code so far
var str = "{'val1': 1, 'val2': 2, 'val3': 3}";
var obj = jQueryparseJSON( str );
alert(obj.val1);
In Firebug I am getting the following errors:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I know the solution is more than likely very simple, but I have been repeatedly overlooking it.
The test string in your sample code is not valid JSON:
var str = '{"val1": 1, "val2": 2, "val3": 3}';
var obj = jQuery.parseJSON( str );
alert(obj.val1);
Now, if you're doing all this because some service is making that object available as a JSON string, it's probably the case that jQuery will do the parsing step for you anyway. If you're just trying to include an object literal into your JavaScript code, then there's no reason to involve the JSON services at all:
var obj = { val1: 1, val2: 2, val3: 3 };
creates an object.
Note that JSON syntax is stricter than JavaScript object literal syntax. JSON insists that property names be quoted with double-quote characters, and of course values can only be numbers, strings, booleans, or null.
Your string is not valid JSON. Object keys must be surrounded with double quotes, not single quotes.
var str = '{"val1": 1, "val2": 2, "val3": 3}';
var obj = jQuery.parseJSON(str);
alert(obj.val1);
DEMO
function str2json (str, val, obj) {
var obj = str.indexOf("'") != -1
? JSON.parse(str.replace(/'/g, "\""))
: JSON.parse(str);
return (val === undefined ? obj /* JSON.stringify(obj) */ : obj[val])
};
str2json("{'val1': 1, 'val2': 2, 'val3': 3}", "val1"); // `1`
str2json("{'val1': 1, 'val2': 2, 'val3': 3}")
// `obj` : `[object Object]` ,
// `JSON.stringify(obj)` : `{"val1":1,"val2":2,"val3":3}`
jsfiddle http://jsfiddle.net/guest271314/n8jLG/
You have a typo error in your code :
here var obj = jQueryparseJSON( str );
should be var obj = jQuery.parseJSON( str );

Find the length of an JSON object

I have a JSON like the following.
How can I find the length of air in console,
console.log (block.number.path[i].air.length);
{ "block": [
{ "number": "36",
"path": [
{ "air": "[{\"name\":\"0\"},{\"name\":\"1\"},{\"name\":\"2\"}]" },
{ "water": "[{\"name\":\"3\"},{\"name\":\"4\"},{\"name\":\"5\"}]" },
{ "sand": "[{\"name\":\"6\"},{\"username\":\"7\"},{\"name\":\"8\"}]" }
]
}
]
}
air itself contains a JSON encoded array, which you have to decode first:
// your obj in here
var obj = { "..." : "..." };
// grab the respective length of the "air" attribute
var air = JSON.parse( obj.block[0].path[0].air );
console.log( air.length );
http://jsfiddle.net/pLAny/
You can solve this like so:
var length = JSON.parse(block.number.path[i].air).length;
console.log(length);
It kind of looks like some of that JSON got malformed. "air", "water", and "sand" are all JSON arrays...but parsed out into strings. If you're the one generating the JSON, look into that, because it doesn't seem right. As the other answers point out, it's still solvable in Javascript using JSON.parse(), as long as you can be sure your target browsers have that interface (most modern ones).
For any JSON array (anything declared using [] brackets) you can check its .length property.
Given that json is a variable containing your JSON, you can do:
json["block"][0]["path"][0]["air"].length
Block is an array, so you have to access to the element first:
a.block[0].path[0].air.length
where a is the variable where you are holding the data.

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

Categories