Retrieving values of json object in javascript - javascript

I am sending an AJAX request to server and retrieving a response as a json object from the server with javascript code to my android application. I know the key values of the json object(ID, name, status, etc.) but I do not know how to get their values.(100, Mark, success, etc.) I need those data for processing for some other task. Can someone please tell me how to extract data from that json object. When I use alert(http.responseText); as follows I get the json object displayed. I need to get the values out of it.
method used to receive response
http.onreadystatechange = function() { //Handler function for call back on state change.
if(http.readyState == 4) {
alert(http.responseText);
json object I receive
{"header": {"ID":100,"name:"Mark"},"body":{"status":"success"}}

You have to convert The string to an object by doing var response=JSON.parse(http.responseText);
Just treat it like any object - console.log(response['name'])

You need to convert it to a JavaScript object using JSON.parse:
var obj = JSON.parse(http.responseText);
Since some legacy browsers do not have native JSON support you should include json2.js to shim it for those browsers.

you will have to eval the http.responseText to get the json object...
but using eval is not recommended, so you can use the json2 library to parse the text into json object..
or else you can even use the library like jquery and use function parseJSON to get it converted to json object

Related

Reading json file

In my ASP.NET backend I am creating json file from a query, I want to use this json file and take some data from it.
I wrote this code:
$(document).ready(function ()
{
$.getJSON("/Content/smartParkTotalJson.json", function (json)
{
});
}
And now I want to see the json , take some data from it (there are many landmarks inside this json file and I want to take the ID element, latitude and longitude).
How can I get access to the things I'm interested in?
In order to parse your json data, use JSON.parse(). Pretty-printing is implemented through JSON.stringify(); the third argument defines the pretty-print spacing.
$.getJSON("/Content/smartParkTotalJson.json", function(data)
{
var obj = JSON.parse(data);
var obj_str = JSON.stringify(obj, null, 2);
console.log(obj_str);
// ...
});
For reading/traversing json objects in javascript, take a look at this simple tutorial. It can represent a good starting point for understanding the basic principles, and unless you provide an example of your json data, also your only choice to perform your data extraction.

Parsing JSON to populate the dhtmlx grid

I get JSON as a response, from an ajax call, the contents of which I then want to be loaded in the grid.
From the JQuery documentation, http://api.jquery.com/jQuery.ajax/, for response of type JSON:
"json": Evaluates the response as JSON and returns a JavaScript
object.
So I convert the JavaScript object back to JSON using JSON.stringify:
importConfigurationStatusGrid.parse(JSON.stringify(result), "json");
But the grid doesn't get populated.
The response I get looks like this:
{"rows":{"Added to index":["file1", "file2",...."],
"Conflicting":["file3", "file4",..."], "Removed":["file5",
"file6",...."]}}
I checked the JSON format on https://docs.dhtmlx.com/grid__data_formats.html#jsonformat, and I think the difference between the two(the response I get and the format specified) might be the cause.
How can I parse the JSON string using the parse method of dhtmlxGridObject?
result = {"rows":{"Added to index":["file1", "file2",...."], "Conflicting":["file3", "file4",..."], "Removed":["file5", "file6",...."]}}
importConfigurationStatusGrid.parse(result, "json");
Edit 1:
#ogui: I don't know what your AJAX request looks like, but you can add
a dataType property and set it to json so that your result gets
automatically parsed as an object for you.
The ajax request does have a dataType: 'json' property specified. So there isn't a need to use JSON.parse(). The problem lies in converting the JS object to a valid JSON format that the parse(dhtmlx) method requires.
#ogui: You could aso use jQuery.getJSON().
Even if I were to use this method, the grid object would have have to parse the same JSON, which it is failing at.
Use JSON.parse.
result = JSON.parse(result);
I don't know what your AJAX request looks like, but you can add a dataType property and set it to json so that your result gets automatically parsed as an object for you. This is mentioned in the jQuery AJAX documentation page you linked. You could aso use jQuery.getJSON().

Why when sending data over AJAX, do you have to JSON.stringify() your objects?

JSON stands for javascript object notation (as I'm sure you're aware), so why, when sending json via ajax do you need to turn it into a string to send it? Is it simply a formatting thing, or what?
This may belong in another place, if so, let me know, I'll close it and move it.
Obviously, I'm not looking for opinions, I'd like to know the actual answer.
Just to make sure I'm clear, I understand what JSON.stringify() does, and its counterpart JSON.parse(). I just want to know, why using stringify is required.
Thanks!
when sending json via ajax do you need to turn it into a string to send it?
If it isn't a string, then it isn't JSON in the first place.
JSON is a text based data format. HTTP is a text based communications protocol.
JSON stands for javascript object notation
JSON is based on the syntax for JavaScript literals. A JavaScript object is not JSON.
AJAX is all about HTTP requests, which are basically "text" requests to a server. That's the main reason why you have to stringify your object: That way it's turned into text that can "travel" over HTTP.
When sending data to a web server, the data has to be a string.
That's why we are using JSON.stringify() function to convert data to string and send it via XHR request to the server.
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url = "submit.php";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type", "application/json");
// Converting JSON data to string
var data = JSON.stringify({ "name": name.value, "email": email.value });
// Sending data with the request
xhr.send(data);

AJAX responseXML

i have a problem regarding the responseXML of ajax..
I have this code from my callback function:
var lineString = responseXML.getElementsByTagName('linestring')[0].firstChild.nodeValue;
However, the linestring can only hold up to 4096 characters max.. the remaining characters are rejected.
I dont know what to use to get all the values that the lineString
returns. its quite a big data thats why I thought of using the responseXml
of AJAX, BUT turned out it still cannot accomodate everything.
My linestring consists of lines from a logfile which I concatenated and just
put line separator. I need to get this data in my form so that is why after reading from the php, i send it back via AJAX
Do you have suggestions guys.
XML adds a lot of extra markup for most ajax requests. If you are expecting some kind of list with data entities, sending them in a JSON format is the way to go.
I used JSON to get quite huge arrays with data.
First of all, JSON is just Javascript Object Notation meaning that the Ajax Request would request a String which will actually be evaluated as a Javascript object.
Some browsers offer support for JSON parsing out of the box. Other need a little help. I've used this little library to parse the responseText in all webapps that I developed and had no problems with it.
Now that you know what JSON is and how to use it, here's how the PHP code would look like.
$response = [
"success" => true, // I like to send a boolean value to indicate if the request
// was valid and ok or if there was any problem.
"records" => [
$dataEntity1, $dataEntit2 //....
]
];
echo json_enconde($response );
Try it and see what it echos. I used the php 5.4 array declaration syntax because it's cool! :)
When requesting the data via Ajax you would do:
var response
,xhr = getAjaxObject(); // XMLHttp or ActiveX or whatever.
xhr.open("POST","your url goes here");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
response = {
success : false,
//other error data
};
}
if(response.success) {
//your data should be in response
// response.records should have the dataEntities
console.debug(response.records);
}
}
}
Recap:
JSON parsing needs a little help via JSON2 library
PHP can send maps as JSON
Success boolean is widely used as a "successful/unsuccessful" flag
Also, if you're into jQuery, you can just set the dataType : "json" property in the $.ajax call to receive the JSON response in the success callback.

Accessing JSON values with a variable

I'm trying to access JSON data with jQuery and grab a specific set of values based on a variable. I've done this before using [] but for some reason I can't figure out what is going wrong this time.
My JSON file (being read in by getJSON, and named jsonmaker.php) looks like this:
{"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}}
I then have a function which is essentially this:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}
}
But it keeps returning undefined. Any idea what I'm doing wrong? I've checked to make sure the var going to attrib is 0107001, no problems there.
Also, I know my JSON file is a php file so I could filter what's returned to match the attrib value, but I'm looking to develop something that can run purely on HTML and JS, so I could just pack the JSON file for the project and take it with me. No need for a web server w/ PHP etc.
The data access itself works for me:
var data = {"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}};
var attrib = "0107002";
alert(data[attrib].label); // USA
Make sure that attrib remains untouched between the moment you call addAttrib() and the moment when the AJAX request completes and your anonymous callback function gets called.
Update: is this your real code? You have at least one syntax error:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}); // <- Please note missing ");"
}
In my experience, $.getJSON() doesn't always return an object. Depending on the MIME type that the server returns along with the JSON, you might end up with a string instead of an object. Check what data contains. If it's a string, you must manually parse it using eval() (old style) or JSON.parse() (new browsers only).
try to list all properties from data, to have sure the data is being returned:
for (var p in data){
if (data.hasOwnProperty(p){
alert(data[p]);
}
}
It's not your solution but with this you can know how your data is coming.

Categories

Resources