How to fetch data from JSON object in JavaScript? - javascript

I am working on SpringMVC. In my controller I create a JSON object and I pass that object to JavaScript. How can I read that object in JavaScript?
My Map object
Map<String rootNode,List<String>> map = new HashMap<String rootNode,List<String>();
String rootNode = "bhanu";
ArrayList<String> al = new ArrayList<String>();
for( int i = 0; i < UserProfile.size; i++ ) {
al.add( userProfile.get( i ) );
}
map.put( userProfile, al );
At last my Map object has this data:
{
"Bhanu":["hari#gmail.com","balu#gmail.com","santha#gmail.com"],
"root":["bhanu#gmail.com","anu#gmail.com","apar#gmail.com"],
"hari":["bhanuprasad#gmail.com","sravya#gmail.com","mahesh#gmail.com"],
"balu":["rama#gmail.com"]
}
Now I convert this object with GSon:
Gson gson = new GSon();
String orgChartUsers = gson.toJson(map);
Now I passed this string to JavaScript because this is my Ajax response:
function orgUsers( result ) {
var orgObject = JSON.parse( result );
for(var name in result) {
console.log(name + "=" + result[name]);
}
}
This is working fine but i want to fetch data like this
first i want to fetch data from "root" in root i have some data when i read root for example i got bhanu#gmail.com now i want to fetch the data from Bhanu here i got some data like hari#gmail.com again i want to fetch data for hari like this i want how can i do this any one help me

Your lists will become javascript arrays, so for example you could use:
window.alert (orgObject["Bhanu"][0]);
which should pop up "hari#gmail.com" given your example data.
See How to list the properties of a JavaScript object for details of how to list the keys of your map, should you need this.

The result will be either an object or array.
To iterate over objects you can use the for-in loop
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
// do something here
}
}
To iterate over an array you can use a normal loop:
for (var i = 0, ilen = array.length; i < ilen; i += 1) {
// do something here
}

Here is the most simple way
var result = {"Bhanu":["hari#gmail.com","balu#gmail.com","santha#gmail.com"],"root":["bhanu#gmail.com","anu#gmail.com","apar#gmail.com"],"hari":["bhanuprasad#gmail.com","sravya#gmail.com","mahesh#gmail.com"],"balu":["rama#gmail.com"]};
for(var name in result) {
console.log(name + "=" + result[name]);
}
This outputs:
Bhanu=hari#gmail.com,balu#gmail.com,santha#gmail.com
root=bhanu#gmail.com,anu#gmail.com,apar#gmail.com
hari=bhanuprasad#gmail.com,sravya#gmail.com,mahesh#gmail.com
balu=rama#gmail.com
Have in mind that the arrays are actually cast to a string. So result[name] is actually an array.

Related

Get JSON data after it's stored in a variable

After getting JSON back from the ajax call, the data "response" is stored in the "theObj" variable; however, when I try to log "theObj" to the console, it results in multiple "[Object object]", even with JSON.stringify().
If I do a "theObj[0]" (response.results[0] works fine), I get "[", for the first character in "[Object object]".
Q: How can I store JSON in a variable and get the data back out afterward?
$.ajax(settings).done(function(response) {
for (var i = 0; i < 19; i++) {
//creating JSONenter[enter image description here][1]
theObj += response.results[i];
if (i == 18) {
//console.log(theObj.id)
console.log(JSON.stringify(theObj[0].id))
}
}
}
I think the error is in the line
theObj += response.results[i];
So try this instead
function (response) {
var list = response.results;
// if there is no reason for having 19, replace this with var end = list.length
var end = Math.min(list.length, 19);
for(var index = 0; index < end; index++) {
theObj.push(list[index]);
}
console.log(theObj);
}
We don't see the initialization of theObj variable
If it is an array you should use the push function to add elements to it
If it is a common object then use theObj[id] = list[index];
DISCOURAGED If it is a string then you should use theObj += JSON.stringify(response.results[i];) + ", ";, then make sure that you add } or ] at the end if it is an object or array respectively (and that it has also has { or [ in the begining) and then use JSON.parse(theObj) to convert it back to an object
Please let me know which of the above are you using
try this
$.ajax(settings).done(function(response) {
$.each( response, function( key, val ) {
console.log(val.id)
});
}
I assumed you want to get the data as object and not a string.
For that you have to use var object = JSON.parse(yourJSONString). This method returns an object based on your JSON string.
Example:
JSON result:
{
"name":"John Doe"
}
Javascript code:
var john = JSON.parse(result);
console.log(john.name); //prints John Doe

Add dynamic key-values to JSON object

I'm trying to create a json object in javascript containing dynamic values. I need to pass this JSON Object to server through an AJAX call. But I'm unable to add the dynamic values.
var finalJSONObj={};
for loop(int i = 0; i<10;i++){
// gets the values of rows i need to add ..
var taskValue = tasks[i]; // need to add this in the JSON Object
}
My final JSON object should look like:
finalJSONObj = {
tasks1: 'taskValue',
tasks2: 'taskValue',
tasks3: 'taskValue',
tasks4: 'taskValue',
userId: 'abcd',
date: '23/09/2016'
};
Need to add the "taskValue" retrieved from the for loop for each task in the JSON Object. Any Thoughts?
How about:
var finalJSONObj={};
for (var i = 0; i<tasks.length; i++) {
finalJSONObj[('tasks' + (i+1))] = tasks[i];
}
You are doing it wrong.
In forloop just change this syntax
var finalJSONObj={};
for loop(int i = 0; i<10;i++){
// gets the values of rows i need to add ..
finalJSONObj['task'+ (i + 1)] = tasks[i]; // need to add this in the JSON Object
}
Here key will be task + i which will be task1, task2 etc and value will be mapped to this key from your tasks array.

How can I convert an array of key value pair objects into an associative array in javascript

You guys never let me down and I am kind of in a tight spot on this one, I needed to maintain the order of a java map while converting it into a JSON object, I realized that this was nearly impossible and decided that I would use a JSON array. The only way that this would work for my particular data however was to use a JSON array of JSON objects. so it looks like this:
[{"2014-11-18":0},{"2014-11-19":0},{"2014-11-20":0},{"2014-11-21":0},{"2014-11-22":0},{"2014-11-23":0},{"2014-11-24":0}]
the code that got me here:
public static JSONArray dataGenerationDay(ArrayList<String> comp, int days) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("MM-dd-yyyy");
Map<LocalDate, Integer> compMap = new TreeMap<LocalDate, Integer>();
JSONArray orderedJSON = new JSONArray();
//create map of data with date and count
for (String date : comp) {
DateTime dt = formatter.parseDateTime(date);
LocalDate dateTime = new LocalDate(dt);
if (!compMap.containsKey(dateTime)) {
compMap.put(dateTime, 1);
} else {
int count = compMap.get(dateTime) + 1;
compMap.put(dateTime, count);
}
}
//if there were days missing in the DB create those days and put them in the map
//with a zero count
if (compMap.size() < days){
LocalDate today = LocalDate.now();
for (int i = 0; i < days; i++){
LocalDate dayCount = today.minusDays(days- i);
if (!compMap.containsKey(dayCount)) {
compMap.put(dayCount, 0);
}
}
}
//json object does not hold order of tree map, create json array
//of ?json objects? to maintain order for the graph
for (Map.Entry<LocalDate,Integer> entry : compMap.entrySet()){
JSONObject object = new JSONObject();
object.put("" + entry.getKey(), entry.getValue());
orderedJSON.put(object);
//test the order of the map for validity
System.out.println("Key Value Pair Is: " + entry.getKey() + " : " + entry.getValue());
}
//test the order of the array for validity
System.out.println("Ordered JSON List: " + orderedJSON.toString());
return orderedJSON;
}
Hope my code is up to par, trying to keep it as clean as possible???
However back to the issue. This works great, the problem I am having however is converting this array of objects into an associative array in javascript so that I can use it for my D3js bar graph here is the code that I foolishly tried but failed with
var dateToArray = function(json_object) {
var dayArray = [];
for (key in json_object){
dayArray.push({
"Date" : key[0],
"Count" : json_object[key[1]]
});
}
console.log("Here is su array" + dayArray);
return dayArray;
};
Any Ideas?
Try this
var dateToArray = function(json_object) {
var dayArray = [],
key;
for (var i = 0; i < json_object.length; i++) {
key = Object.keys(json_object[i])[0];
dayArray.push({
"Date" : key,
"Count" : json_object[i][key]
});
}
return dayArray;
};
json_object is Array not Object and you should not use for (..in..) (for(..in..) statement iterates over the enumerable properties of an object). In my example I use Object.keys which return array of keys in object, and you can get value by key in Object because in JS for get property from object there are two ways like obj.key or obj[key];
Demo: http://jsbin.com/ruseja/1/edit

How to return all objects in javascript array

I have a variable that is created by Flowplayer and available via javascript. If I write the variable to the page directly it just returns 'object Object' so I am assuming this is an array. If I don't know the names of any of the objects inside the array, how can I parse out the data inside?
I know I am missing something really fundamental here, but I don't think I have ever had to get data from an array not knowing what it contains.
Notes:
What I am trying to do is get the onCuePoint caption data embedded
into an RTMP video stream
.valueOf() returns the same thing
Here is the code I am using that returns 'object Object':
streamCallbacks: ['onFI'],
clip:
{
live:true,
provider: 'rtmp',
autoPlay: true,
url:'test1',
onFI:function(clip, info)
{
document.getElementById("onFI").innerHTML += "Data: " + info;
}
}
Thank you
If what you are asking is how you iterate over the contents of an array, you can do so in plain javascript like this:
var arr = [1,2,3];
for (var i = 0; i < arr.length; i++) {
// arr[i] is each item of the array
console.log(arr[i]);
}
Just because something is of type Object does not necessarily mean that it's an array. It could also just be a plain object with various properties on it. If you look at the info argument in either the debugger or with console.log(info), you should be able to see what it is.
You need to iterate through your array and get the results one by one, replace your onFI function with this :
onFI:function(clip, info)
{
var data = "";
// For each value in the array
for (var i = 0; i < info.length; i++)
{
// Add it to the data string (each record will be separated by a space)
data += info[i] + ' ';
}
document.getElementById("onFI").innerHTML += "Data: " + data;
}

Find specific key value in array of objects

This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}

Categories