Cannot retrieve data from javascript json object created in javascript - javascript

I have a servlet where it returns a string like [["one","two"],["one","two"]], which is an array representation.
This was sent to the front end using the Gson library's toJson() method as a String. It sends this String array along with some other attributes in JSON format and then I'm using the toJson() method to send it to front end.
In the Ajax response handling, I'm doing a $.parseJSON() on the object and retrieving the values. (It works fine and I was able to retrieve that array string.)
Now in JavaScript I need to create another JSON object with some other values along with this string array and send it to another JavaScript method. But in that method I cannot retrieve the values. My motive is to extract this array string as an array and iterate it.
Following is what I do in JavaScript to send to JavaScript method:
var streamId = stream + CONSTANTS.colon + streamVersion;
var eventsData = {};
var jsonData = [];
eventsData ["source"] = streamId;
eventsData ["data"] = eventsArray;
jsonData.push(eventsData);
onSuccessFunction(jsonData);
In onSuccessFunction I tried to get jsonData.data, but it says undefined.
Any suggestions?

Related

how can i take json data and read it into javascript object?

how can i take this json data (either from website or pasted into local file) and read it into a javascript object?
Here is the json data: https://jsonblob.com/b914b62a-e276-11e7-8a9c-f99a86745e2b
You can convert an JSON file to an object by using JSON.parse
let convertedObject = JSON.parse(text)
There are not many differences between a JSON string and a Javascript Object. In fact Everything is an object in javascript, from functions to arrays...well coming back to your question you can get the value stored in a JSON string by parsing the JSON string by using JSON.parse() function and then call it as you generally do with JS objects. for Example: -
var jsonString = JSON.stringify({key: "val"}); // here i am converting a regular object to JSON string
var jsonToObj = JSON.parse(jsonString);
console.log(jsonToObj.key);

Access specific part of JSON JS

I am trying to access the t part of the "data": object below. I am doing this by doing console.log(message.data.f) however this returns undefined. I do not understand why I cannot access it in this way. See object below:
"data":"{\"e\":\"53845\",\"f\":\"SCORE\",\"pf\":[{\"p\":\"HOME\",\"v\":\"0\"},{\"p\":\"AWAY\",\"v\":\"0\"}],\"^t\":\"f\",\"i\":\"357575\",\"z\":1492771602631}",
Note I have marked the part of the object I wish to access with a ^
Your data property is a JSON string and probably all the object is a JSON string.
You need to parse the string as JSON
var obj = JSON.parse(myObj.data);
and then you can access:
console.log(obj.f);
If your first object, the one containing data, is not already a JSON too and its name is for example myFirstObject you need to do just this:
var jsonObj = JSON.parse(myFirstObject);
console.log(jsonObj.f);
Your message is nothing but string. Parse it first to a corresponding object to access its variables.
var parsed = JSON.parse(message);
console.log(message.data.t);

How to retrieve value from json of one array and one int literal in javascript

I am passing data back to java script through a rest api. The rest API return data in the following below mentioned structure.I am confused what format of json is it and how can i iterate on the array inside and get the int value individually.
The format of my response is like :
{"searchOrder":[
{"location":"10","trackingId":"656"},
{"location":"34","trackingId":"324"},....],
"count":100}
i want searchOrder as array of json to display in table and count to show total row.How can i get them?
Just iterate over the array and extract the values
// Turn the JSON into a JS object (maybe in your XHR handler)
var data = JSON.parse(jsonString); // jsonString could be responseText from XHR
var arrayOfTrackingIdValues = data.searchOrder.map(function (value) {
return value.trackingId;
});
JavaScript provide built-in function JSON.parse() to convert the string into a JavaScript object and drive/iterate the each element based on type obj/array
var obj = JSON.parse(text);

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.

Issue mapping Json string with ko.mapping

On the server side I have a Asp.Net Web application, a WebMethod returns a Json string serialized just like this one:
Object { d= "[{"Id":"1","Name":"COMERCIAL BANK"},
{"Id":"2","Name":"AZTEC BANK"},
{"Id":"3","Name":"EL SALVADOR BANK"}]" }
When I try mapping that result using var mappedBanks = ko.mapping.fromJSON(data.d), and then use console.log(mappedBanks) all I get printed is c() and is like that mappedBanks, that should be an array, has no elements because I can iterate on it and when I try to print the first element, the console says undefined. Is there a problem with the Json? or I´m not mapping it right.
ko.mapping.toJSON requires first argument to be an object, not an array. Your option is to make your JSON-encoded array to be property value.
var mappedBanks = ko.mapping.fromJS({ items: JSON.parse(data.d) });
console.log(mappedBanks.items);

Categories

Resources