Javascript: Parse JSON output result - javascript

How can i retrieve the values from such JSON response with javascript, I tried normal JSON parsing seem doesn't work
[["102",true,{"username":"someone"}]]
Tried such codes below:
url: "http://somewebsite.com/api.php?v=json&i=[[102]]",
onComplete: function (response) {
var data = response.json[0];
console.log("User: " + data.username); // doesnt work

var str = '[["102",true,{"username":"someone"}]]';
var data = JSON.parse(str);
console.log("User: " + data[0][2].username);
Surround someone with double quotes
Traverse the array-of-array before attempting to acces the username property
If you are using AJAX to obtain the data, #Alex Puchkov's answer says it best.

So the problem with this is that it looks like an array in an array. So to access an element you would do something like this.
console.log(obj[0][0]);
should print 102
Lets say you created the object like so:
var obj = [["102",true,{"username":someone}]];
this is how you would access each element:
obj[0][0] is 102
obj[0][1] is true
and obj[0][2]["username"] is whatever someone is defined as
From other peoples answers it seems like some of the problem you may be having is parsing a JSON string. The standard way to do that is use JSON.parse, keep in mind this is only needed if the data is a string. This is how it should be done.
var obj = JSON.parse(" [ [ "102", true, { "username" : someone } ] ] ")

It depends on where you are getting JSON from:
If you use jQuery
then jQuery will parse JSON itself and send you a JavaScript variable to callback function. Make sure you provide correct dataType in $.ajax call or use helper method like $.getJSON()
If you getting JSON data via plain AJAX
then you can do:
var jsonVar = JSON.parse(xhReq.responseText);

Related

access javascript object in servlet [duplicate]

I am creating and sending a JSON Object with jQuery, but I cannot figure out how to parse it properly in my Ajax servlet using the org.json.simple library.
My jQuery code is as follows :
var JSONRooms = {"rooms":[]};
$('div#rooms span.group-item').each(function(index) {
var $substr = $(this).text().split('(');
var $name = $substr[0];
var $capacity = $substr[1].split(')')[0];
JSONRooms.rooms.push({"name":$name,"capacity":$capacity});
});
$.ajax({
type: "POST",
url: "ParseSecondWizardAsync",
data: JSONRooms,
success: function() {
alert("entered success function");
window.location = "ctt-wizard-3.jsp";
}
});
In the servlet, when I use request.getParameterNames() and print it out to my console I get as parameter names rooms[0][key] etcetera, but I cannot parse the JSON Array rooms in any way. I have tried parsing the object returned by request.getParameter("rooms") or the .getParameterValues("rooms") variant, but they both return a null value.
Is there something wrong with the way I'm formatting the JSON data in jQuery or is there a way to parse the JSON in the servlet that I'm missing?
Ask for more code, even though the servlet is still pretty much empty since I cannot figure out how to parse the data.
The data argument of $.ajax() takes a JS object representing the request parameter map. So any JS object which you feed to it will be converted to request parameters. Since you're passing the JS object plain vanilla to it, it's treated as a request parameter map. You need to access the individual parameters by exactly their request parameter name representation instead.
String name1 = request.getParameter("rooms[0][name]");
String capacity1 = request.getParameter("rooms[0][capacity]");
String name2 = request.getParameter("rooms[1][name]");
String capacity2 = request.getParameter("rooms[1][capacity]");
// ...
You can find them all by HttpServletRequest#getParameterMap() method:
Map<String, String[]> params = request.getParameterMap();
// ...
You can even dynamically collect all params as follows:
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String name = request.getParameter("rooms[" + i + "][name]");
if (name == null) break;
String capacity = request.getParameter("rooms[" + i + "][capacity]");
// ...
}
If your intent is to pass it as a real JSON object so that you can use a JSON parser to break it further down into properties, then you have to convert it to a String before sending using JS/jQuery and specify the data argument as follows:
data: { "rooms": roomsAsString }
This way it's available as a JSON string by request.getParameter("rooms") which you can in turn parse using an arbitrary JSON API.
Unrelated to the concrete problem, don't use $ variable prefix in jQuery for non-jQuery objects. This makes your code more confusing to JS/jQuery experts. Use it only for real jQuery objects, not for plain vanilla strings or primitives.
var $foo = "foo"; // Don't do that. Use var foo instead.
var $foo = $("someselector"); // Okay.

Converting json array to query string gives null

What I am trying to achieve is to send a json object as a querystring to an API.
The json object I have is:
{
"Name":"Dlsajdsa",
"ImageUrls":["/Images/Facility/8353/85e26a18-4366-4412-b37a-72d94f2ccda5.jpg"]
}
I would like to convert this to something like ?Name=&ImageUrls=
However, when using $.param(json) I get the following:
?Name=Dlsajdsa&ImageUrls%5B%5D=%2FImages%2FFacility%2F8353%2F85e26a18-4366-4412-b37a-72d94f2ccda5.jpg
This result, on the API point of view, that the ImageUrls array is null.
What am I missing here?
you can try $.param(json,true)
Based on the documentation of jQuery.param, I'd say this is the piece of code you want to use:
var json = {
"Name":"Dlsajdsa",
"ImageUrls":["/Images/Facility/8353/85e26a18-4366-4412-b37a-72d94f2ccda5.jpg"]
};
var recursiveDecoded = decodeURIComponent($.param(json));
// "Name=Dlsajdsa&ImageUrls[]=/Images/Facility/8353/85e26a18-4366-4412-b37a-72d94f2ccda5.jpg"
The query parameter is called ImageUrls%5B%5D, that means ImageUrls[], not ImageUrls as you expect.

Json associative array accessing in jQuery

I am getting response in below format for every product and in a single call there can be many products. I am trying to access this data via jQuery but I'm not able to access it.
Productdata['someid'] = { "Product Json data"}
I am using below syntax in jQuery but not getting the data. Please suggest.
alert(Productdata['someid']);
Its not going as JSON format .
JSON is a key : value pair format ;
so your Productdata should be in below format:
Productdata = { 'someid' : "Product Json data"}
A Json like this
var data={"name":"somebody"};
To call
return data.name
Or
return data["name"]
The problem here is that JavaScript does not support associative arrays (scroll down to "Associative arrays, no way!"). It has some internal workarounds which make it appear as if it does, but really all it does is just adding the keys as properties.
So you would most likely be able to access it using Productdata.someid = ....
EDIT:
So assuming you have the following JSON string: {"id":"123"} (which is valid JSON), you can use it like this:
var jsonString = '{"id":"123"}';
var parsedJSON = $.parseJSON(jsonString);
var productID = "product_" + parsedJSON.id;
Does this help?
Some useful links: JSON format checker to make sure the JSON is valid.
Unfortunately I wasn't allowed to add more than 2 links, so the jQuery parseJSON function link is still in the comment below.

Proper use of eval in javascript?

So I have this json object where the structure is variable depending on how you retrieve the data. Lets say the object looks like this in one case:
{
"status": "success",
"data": {
"users": [...]
}
}
but looks like this in another case:
{
"status": "success",
"data": {
"posts": [...]
}
}
Now for the first example, they way I am dynamically getting the data is like this:
var dataLocation = 'data.users';
var responseData;
eval('responseData = response.' +dataLocation + ';');
This allow me to configuration it. Just note that this is just a simple example, in the real code there is only one function to parse the data and I would be passed dataLocation in as a parameter.
Now my first question is whether or not there is a better want to accomplish the same goal without using eval?
If not, the second question is what do I need to do to the eval statement to make sure it is safe (dataLocation should never be passed in from a user, it will always come from code but still).
UPDATE
Based on the comment from Bergi, I am now using this:
var parts = dataListLocation.split('.');
for(var x = 0; x < parts.length; x += 1) {
responseData = responseData[parts[x]];
}
You should use bracket notation instead of eval:
var responseData = response['data']['users'];
Note: from your description, what you have is a JavaScript object literal. A JSON would be that same object encoded as a string (with JSON.stringify, for example). There is no such thing as a "JSON object", you either have a JavaScript object, or a JSON string.
You can use key indexers for objects in JS:
var responseData response.data['users]';
That is after getting rid of the data. in our dataLocation

New to JSON, what can I do with this json response

A website returns the following JSON response, how would I consume it (in javascript)?
[{"ID1":9996,"ID2":22}]
Is JSON simply returning an array?
We use:
function evalResponse(response) {
var xyz123 = null;
eval("xyz123 = " + response);
return xyz123;
}
An alternative method is to simply use:
var myObj = eval(response);
Basically, you have to call eval() on the response to create a javascript object. This is because the response itself is just a string when you get it back from your AJAX call. After you eval it, you have an object that you can manipulate.
function myCallback(response) {
var myObj = evalResponse(response);
alert(myObj.ID1);
}
You could use a javascript library to handle this for you. Or, you could try to parse the string yourself. eval() has it's own problems, but it works.
If you use http://www.JSON.org/json2.js you can use it's method JSON.parse to retrieve the json string as an object (without the use of eval (which is considered evil)), so in this case you would use:
var nwObj = JSON.parse('[{"ID1":9996,"ID2":22}]');
alert(nwObj.ID1); //=> 9996
It looks like an array with a single object holding two properties. I'd much prefer to see the same data structured like this:
{"ID":[9996,22]}
Then you have a single object holding an array with two elements, which seems to be a better fit for the data presented. Then using Endangered's evalResponse() code you could use it like this:
var responseObj = evalResponse(response);
// responseObj.ID[0] would be 9996, responseObj.ID[1] would be 22
I think the other answers might not answer your question, maybe you're looking for a way to use that "array of 1 object". Maybe this can help:
var arr = [{"ID1":9996,"ID2":22}];
var obj = arr[0];
var id1 = obj.ID1;
var id2 = obj.ID2;
Here's how you get to your data:
<script type="text/javascript" >
var something = [{"ID1":9996,"ID2":22}]
alert(something[0].ID1)
</script>
The JSON you posted represents an array containing one object, which has attributes ID1 and ID2 (initialized to the respective values after the colon).
To convert the string to a javascript object, pass it to eval, like this:
var obj = eval('[{"ID1":9996,"ID2":22}]');
However, this method will fail if you only have a single object instead of an array, so it is safer to wrap it in parenthesis:
var obj = eval('(' + jsonResponse + ')');

Categories

Resources