I have some JSON with two parameters expressed as
{"pushid":"35336165333161382d646338302d346665302d626236312d303763313435663036656131","count":1}
I'm trying to get access to the "pushid" and the "count" as usable elements, either in an object, an array or a map, and am a little confused as to how to do that.
When I call JSON.parse(json) it returns undefined, and so I assume that it's already an object. However, when I try to use json[1] it returns the second character of the whole thing (which in this case is "). How do I make an object
var obj = {pushId: SOME_STRING, count: SOME_INT)?
Thanks in advance,
Considering:
var jsonString = '{"pushid":"35336165333161382d646338302d346665302d626236312d303763313435663036656131","count":1}';
You can do:
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.pushid); // 3533...
console.log(jsonObj['pushid']); // 3533...
console.log(jsonObj.count); // 1
console.log(jsonObj['count']); // 1
console.log(jsonObj[0]); // undefined
console.log(jsonObj[1]); // undefined
This is already an object so you don't have to parse it. {"pushid":"35336165333161382d646338302d346665302d626236312d303763313435663036656131","count":1}
All you have to do is now assign it to what ever variable you want.
let data = {"pushid":"35336165333161382d646338302d346665302d626236312d303763313435663036656131","count":1};
console.log("pushid : " + data["pushid"]);
pushid : 35336165333161382d646338302d346665302d626236312d303763313435663036656131
console.log("count : " + data["count"]);
count : 1
I mean, that number is too long for JS to represent in it's 64 bit floating point internal representation, but you can try to parse the base16 repr with
parseInt(obj.pushid, 16);
Related
So i am trying to display a data from an API using JavaScript but got an undefined instead when i console.log(data) what i am getting is like below. its an object but some how its encapsulate as a string? Any idea how to covert this into a actual object i am new with JavaScript api so i am a bit confused.
{"msg":"{\"part\":\"test\",\"station\":\"test2\"}"}
I already tried to de serialize the data using JSON.parse(data) but no luck.
What you have posted is actually an object with a property msg which is a strigified JSON. In order to get proper json from this try obj.msg = JSON.parse(obj.msg); Assuming obj is the response variable you can name it what you want.
See below snippet.
{"msg":"{\"part\":\"test\",\"station\":\"test2\"}"}
const obj = {"msg":"{\"part\":\"test\",\"station\":\"test2\"}"} ;
console.log('Before parsing:' + typeof obj.msg); // string
obj.msg = JSON.parse(obj.msg);
console.log('After Parsing:' + typeof obj.msg); // object
Hope this helps :)
JSON.parse transforms a string-like-object to the object. So, it expects the whole of the object as a string. Which is not happening in your case.
You have an object key msg and its value is a string-like-object. So You need to convert the msg value to the JSON.
a couple of ways to try -
let resp = JSON.parse(data.msg)
or
return JSON.parse(data.msg)
I'm learning Google Maps API; a call to its geolocation API returns a giant JSON string (sample: https://maps.googleapis.com/maps/api/geocode/json?address=66+Fort+Washington+Avenue+New+Yor,NY&key=AIzaSyAGLzbjA0rEl5whQgiuZZdIGVzPZzLv9Kg). If I'm looking for a particular key/value pair out of that resulting set of data to use in my Java script application, is it better to convert that JSON string into an object (parse) and then traverse that object for that key/value pair, or is it Ok just to traverse the returned JSON string itself? What are the pros/cons of each?
Parsing the JSON will always result in easier to read code and is less sensitive to changes in the data that you are receiving. However, if you are looking at pure performance it depends on how unique the data is that you are searching for in the returned JSON string, and how many searches you are doing. If you (for instance) just wanted the lat/long location from the returned string you mentioned above then you could do this:
var index = string.search("location");
var index2 = string.substring(index).search(/-?\d/); // finds first number
lat = parseFloat(string.substring(index+index2));
var index3 = string.substring(index+index2).search("lng");
var index4 = string.substring(index+index2+index3).search(/-?\d/); // finds first number
lon = parseFloat(string.substring(index+index2+index3+index4));
Or, by parsing it you could do this:
var obj = JSON.parse(string);
lat = obj.results[0].geometry.bounds.northeast.lat;
lon = obj.results[0].geometry.bounds.northeast.lon;
Clearly the parsed version is easier to read. However, I ran this 200000 times each, and found that the string search based approach was slightly more than 4 times faster than the JSON object parsing approach. There may have been other ways to optimize the search based approach but you get the idea.
You should use JSON.parse to turn your string into a JavaScript object before attempting to access its properties. You cannot "traverse the returned JSON string itself":
var json = '{ "property": "value" }'
// JSON strings cannot be traversed
console.log(typeof json) //=> "string"
console.log(json.property) //=> undefined
var object = JSON.parse(json)
// Objects can be traversed
console.log(typeof object) //=> "object"
console.log(object.property) //=> "value"
If the api is returning json inside an string, you could parse it and just go throught the elements till you find what you need. Otherwise how would you traverse the string? From my point of view, that's something you shouldn't do.
I have the following json object samples, i.e.:
{"id":"value1" , "time":"valuetime1"}
{"id":"value2" , "time":"valuetime2"}
{"id":"value3" , "time":"valuetime3"}
{"id":"value4" , "time":"valuetime4"}
{"id":"value5" , "time":"valuetime5"}
{"id":"value6" , "time":"valuetime6"}
{"id":"value7" , "time":"valuetime7"}
{"id":"value8" , "time":"valuetime8"}
Based on the above, I would like to add all these json objects to an array, where I can then process and access the array for each json object and extract id1 value together with time1 value and so forth.
I believe I have to use JSON.parse but unsure of how to firstly add these objects to an array and then be able to also parse and access each object's data.
Think of each row above as a separate JSON object which I would like added to an array that is parsed.
Read the file line by line (each line is a separate json)
Parse the line json text to JavaScript object
Put/push/append JavaScript object into a JavaScript array
This is not valid JSON, so JSON.parse would not work, but assuming you have the text in a string variable, you can convert it to JSON with something like:
data = "[" + data.replace(/\}/g, "},").replace(/,$/,"") + "]";
and then parse it.
UPDATE:
var array = [];
// for each input line
var obj = JSON.parse(line);
array.push(obj);
var id = obj.id;
var time = obj.time;
...
Appreciate the responses but I believe I have managed to solve my own question.
Furthermore, as #Mr. White mentioned above, I did have my property names in error which I have now sorted - thanks.
Using the data above, all I was after was the following:
UPDATED
var s = '{"id":"value1","time":"valuetime1"},{"id":"value2","time":"valuetime2"},{"id":"value3","time":"valuetime3"},{"id":"value4","time":"valuetime4"},{"id":"value5","time":"valuetime5"}, {"id":"value6","time":"valuetime6"},{"id":"value7","time":"valuetime7"},{"id":"value8","time":"valuetime8"}';
var a = JSON.parse('[' + s + ']');
a.forEach(function(item,i){
console.log(item.id + ' - '+ item.time);
});
Thanks for the heads up #torazaburo - have updated my answer which I should've done much earlier.
I have not worked too much on javascript. And, I need to parse a JSON string. So, I want to know what exactly JSON.parse does. For example :
If I assign a json string to a variable like this,
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now when I print 'ab', I get an object.
Similarly when I do this :
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
var rs = JSON.parse(pq);
The 'rs' is the same object as 'ab'. So what is the difference in two approaches and what does JSON.parse did differently ?
This might be a silly question. But it would be helpful if anybody can explain this.
Thanks.
A Javascript object is a data type in Javascript - it's have property and value pair as you define in your first example.
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now What is Json : A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other)
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
so it's is a String With json Format.
and at last JSON.parse() Returns the Object corresponding to the given JSON text.
Here is my explanation with a jsfiddle.
//this is already a valid javascript object
//no need for you to use JSON.parse()
var obj1 = {"name":"abcd", "details":"1234"};
console.log(obj1);
//assume you want to pass a json* in your code with an ajax request
//you will receive a string formatted like a javascript object
var str1 = '{"name":"abcd", "details":"1234"}';
console.log(str1);
//in your code you probably want to treat it as an object
//so in order to do so you will use JSON.parse(), which will
//parse the string into a javascript object
var obj2 = JSON.parse(str1);
console.log(obj2);
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
Your 'ab' variable isn't a string, it is a proper javascript object, since you used the {} around it. If you encased the whole thing in "" then it would be a string and would print out as a single line.
Data Type!! That is the answer.
In this case, ab is an object while pq is a string (vaguely speaking). Print is just an operation that displays 'anything' as a string. However, you have to look at the two differently.
String itself is an object which has properties and methods associated with it. In this case, pq is like an object which has a value: {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}} and for example, it has a property called length whose value is 66.
But ab is an object and you can look at name and details as its properties.
What JSON.parse() did differently was that, it parsed (converted) that string into an object. Not all strings can be parsed into objects. Try passing {"name":"abc" and JSON.parse will throw an exception.
Before parsing, pq did not have any property name. If you did something like pq.name, it'll return you undefined. But when you parsed it using JSON.parse() then rs.name will return the string "abcd". But rs will not have the property length anymore because it is not a string. If you tried rs.length then you'll get a value undefined.
I have a string: items[0].name that I want to apply to a JSON object: {"items":[{"name":"test"}]} which is contained in the variable test. I want to apply that string to the object in order to search it (test.items[0].name). I can only think of one way to do this: parse the square brackets and dots using my own function. Is there another way I can do this? Perhaps using eval? (Even though I'd LOVE to avoid that...)
For clarity:
I have a JSON object, what is inside of it is really irrelevant. I need to be able to query the object like so: theobject.items[0], this is normal behaviour of a JSON object obviously. The issue is, that query string (ie. items[0]) is unknown - call it user input if you like - it is literally a string (var thisIsAString = "items[0]"). So, I need a way to append that query string to theobject in order for it to return the value at theobject.items[0]
function locate(obj, path) {
path = path.split('.');
var arrayPattern = /(.+)\[(\d+)\]/;
for (var i = 0; i < path.length; i++) {
var match = arrayPattern.exec(path[i]);
if (match) {
obj = obj[match[1]][parseInt(match[2])];
} else {
obj = obj[path[i]];
}
}
return obj;
}
var name = locate(test, 'items[0].name');
...JSON doesn't have objects, it's just a string.
If you're dealing with an object (ie: you can reference it using dot/bracket notation) then it's just a JavaScript object/array...
So depending on what the deal is, if you're dealing with a 100% string:
'{"name":"string","array":[0,1,2]}'
Then you need to send it through JSON.parse;
var json_string = '{"name":"string","array":[0,1,2]}',
js_obj = JSON.parse(json_string);
js_obj.name; // "string"
js_obj.array; // [0,1,2]
js_obj.array[1]; // 1
If it's not a string, and is indeed an object/array, with other objects/arrays inside, then you just need to go:
myObj.items[0].name = items[0].name;
If it IS a string, then .parse it, and use the parsed object to do exactly what I just did.
If it needs to be a string again, to send to the server, then use JSON.stringify like:
var json_string = JSON.stringify(js_obj);
Now you've got your modified JSON string back.
If you need to support GhettoIE (IE < 8), then download json2.js from Douglas Crockford, and add that script on the page conditionally, if you can't find window.JSON.