Looping to Parse JSON Data - javascript

Description and Goal:
Essentially data is constantly generated every 2 minutes into JSON data. What I need to do is retrieve the information from the supplied JSON data. The data will changed constantly. Once the information is parsed it needs to be captured into variables that can be used in other functions.
What I am stuck in is trying to figure out how to create a function with a loop that reassigns all of the data to stored variables that can later be used in functions.
Example information:
var json = {"data":
{"shop":[
{
"carID":"7",
"Garage":"7",
"Mechanic":"Michael Jamison",
"notificationsType":"repair",
"notificationsDesc":"Blown Head gasket and two rail mounts",
"notificationsDate":07/22/2011,
"notificationsTime":"00:02:18"
},
{
"CarID":"8",
"Garage":"7",
"Mechanic":"Tom Bennett",
"notificationsType":"event",
"notifications":"blown engine, 2 tires, and safety inspection",
"notificationsDate":"16 April 2008",
"notificationsTime":"08:26:24"
}
]
}};
function GetInformationToReassign(){
var i;
for(i=0; i<json.data.shop.length; i++)
{
//Then the data is looped, stored into multi-dimensional arrays that can be indexed.
}
}
So the ending result needs to be like this:
shop[0]={7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18 }
shop[1]={}

You can loop through your JSON string using the following code,
var JSONstring=[{"key1":"value1","key2":"value2"},{"key3":"value3"}];
for(var i=0;i<JSONstring.length;i++){
var obj = JSONstring[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
//based on the result create as you need
}
}
Hope this helps...

It sounds to me like you want to extract the data in the "shop" property of the JSON object so that you can easily reference all of the shop's items. Here is an example:
var json =
{
"data":
{"shop":
[
{"itemName":"car", "price":30000},
{"itemName":"wheel", "price":500}
]
}
},
inventory = [];
// Map the shop's inventory to our inventory array.
for (var i = 0, j = json.data.shop.length; i < j; i += 1) {
inventory[i] = json.data.shop[i];
}
// Example of using our inventory array
console.log( inventory[0].itemName + " has a price of $" + inventory[0].price);

Well, your output example is not possible. You have what is a list of things, but you're using object syntax.
What would instead make sense if you really want those items in a list format instead of key-value pairs would be this:
shop[0]=[7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18]
For looping through properties in an object you can use something like this:
var properties = Array();
for (var propertyName in theObject) {
// Check if it’s NOT a function
if (!(theObject[propertyName] instanceof Function)) {
properties.push(propertyName);
}
}
Honestly though, I'm not really sure why you'd want to put it in a different format. The json data already is about as good as it gets, you can do shop[0]["carID"] to get the data in that field.

Related

Create JSON for chart Data

I want to create a dummy json data and use it for highChart.
This is how I am creating json array
var summaryData = {
WestWorld:[
{"Jan":7894},
{"Feb":7845},
{"March":5826},
{"April":7930},
{"May":1589},
{"June":7891},
{"July":9724},
{"August":7403},
{"September":5566},
{"October":7733},
{"November":1186},
{"December":4456}
],
EastWorld:[
{"Jan":7410},
{"Feb":9512},
{"March":7520},
{"April":8510},
{"May":9965},
{"June":72580},
{"July":147},
{"August":4489},
{"September":6685},
{"October":7036},
{"November":8852},
{"December":4569}
]
};
Now I intend to use this data for drawing charts.I am able to retrieve the keys by doing so
for (var key in summaryData){
console.log(summaryData[''+key+'']);
}
It is consoling an two arrays each of twelve objects.
Can I create this json object in a better way & minimize the if & for loop to get it's keys & value
You can setup your JSON like so:
var summaryData = {
WestWorld: {
"Jan":7894,
"Feb":7845,
...
},
EastWorld: {
"Jan":7410,
"Feb":9512,
...
}
};
This way you can access anything directly, without having to loop through the arrays in WestWorld and EastWorld. For example:
summaryData.WestWorld.Jan => 7894
summaryData has two objects that are arrays and in this case array of objects.
This will retrieve one array and its length
console.log((summaryData.EastWorld).length);
Show the first array element which is an object with a single key:value
console.log(summaryData.EastWorld[0]);
to get its value
console.log(summaryData.EastWorld[0].Jan);
A function to retrieve each key:value pair
function show(world) {
var len = (summaryData[world]).length;
var obj = "";
var ii = 0;
for (ii; ii < len; ii += 1) {
obj = summaryData[world][ii];
for (var key in obj) {
console.log(key + ' ==> ' + obj[key]);
}
}
}
show("WestWorld");
show("EastWorld");
To be a true JSON each string need to be double quoted
check with an online JSON Validation..

Javascript arrays

Let's suppose I have an associative array like this one
var client1={
"id":"1"
"category":"Interiorism",
"photo1":"img/ClientCorp/photoClient1.jpg",
"photo2":"img/ClientCorp/photoClient2.jpg",
"photo3":"img/ClientCorp/photoClient3.jpg",
"photo4":"img/ClientCorp/photoClient4.jpg",
};
var client2={
.
.
.
};
allClients=[client1, client2..., clientx];
I want to set up a function that pushs the photo keys in an empty array. The problem is that not all the clients have the same number of photos, so I am using 'for'. Here is the function I wrote
function photoKeys()
{
var keyList=Object.keys(allClients[id]);
var numKey=parseInt(listaKeys.length);
var photoAlbum=[]; //here I want to put the photo URL's
for (i=2; i<=numFotos; i++)
{
????????????
}
}
Here is the problem, how I can write the photo object from the client array whith the i var from the 'for' function?
I tried this but didn't work
for (i=2; i<=numFotos; i++)
{
photoAlbum.push(allClients[id].photo+'i');
}
Your current code would be parsed like this:
photoAlbum.push(allClients[id].photo + 'i');
It would try to evaluate allClients[id].photo and then append the string i. You need to access the property name using bracket notation instead of dot notation.
You also have the symbol and string part backward, photo is the string and i is your index variable.
photoAlbum.push(allClients[id]['photo' + i]);
The big thing to understand is that client in your example isn't an array, it's an object.
var client1={
"id":"1"
"category":"Interiorism",
"photo1":"img/ClientCorp/photoClient1.jpg",
"photo2":"img/ClientCorp/photoClient2.jpg",
"photo3":"img/ClientCorp/photoClient3.jpg",
"photo4":"img/ClientCorp/photoClient4.jpg",
};
You can acquire an object's keys as an array using Object.keys(client1), or you can loop through all an object's keys using for...in syntax.
If you want to feed an arbitrary number (numFotos) of property values from your object into an array called photoAlbum, you can use the following syntax:
var i = 0;
for(var key in client1){
photoAlbum.push(client1[key]);
if(++i >= numFotos){
break; // break out of the loop if i equals or exceeds numFotos
}
}
First of all you should be accessing the photo paths like:
photoAlbum.push(allClients[id]['photo' + i]);
But i would really recommend you to change the format of your client object to something like this:
var client1 = {
"id" :"1"
"category" :"Interiorism",
"photos" : [
"img/ClientCorp/photoClient1.jpg",
"img/ClientCorp/photoClient2.jpg",
...
]
};
Or this, if you need to store those "photo1", "photo2" ids:
var client2 = {
"id" :"1"
"category" :"Interiorism",
"photos" : [
{
"id" : "photo1",
"path" :"img/ClientCorp/photoClient1.jpg"
},
...
]
};
Then you can iterate them way easier like this:
for(var i = 0; i < allClients[id].photos.length; i++){
photoAlbum.push(allClients[id].photos[i]);
//or this for the second format:
//photoAlbum.push(allClients[id].photos[i].path);
}

How can I parse a JSON object containing a colon

I have an object which comes back as part of a return data from a REST server. It is part of an item object.
(I don't have control over the REST server so I can't change the data received):
{
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
What I want to end up with is some control over this, so that I can display the results when a product is selected in my app. It will appear in a modal. I am using Marionette/Backbone/Underscore/JQuery etc. but this is more of a JavaScript question.
I have tried multiple ways of getting at the data with no success. I would like to be able to have the options in a nested array, but I'd be open to other suggestions...
Basically this kind of structure
var Color=('Red', 'Green', 'Blue', 'Orange')
var Size('Small', 'Medium', 'Large')
The Object structure is fine, just need to be able to translate it to an array and take out the 'Option' keyword
Important to mention that I have no idea what the different options might be when I receive them - the bit after Options: might be any form of variation, color, size, flavour etc.
Loop through the parsed JSON and create new keys on a new object. That way you don't have to create the var names yourself; it's automatically done for you, albeit as keys in a new object.
var obj = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
function processObj() {
var newObj = {};
for (var k in obj) {
var key = k.split(':')[1].toLowerCase();
var values = obj[k].split(',');
newObj[key] = values;
}
return newObj;
}
var processedObj = processObj(obj);
for (var k in processedObj) {
console.log(k, processedObj[k])
// color ["Red", "Green", "Blue", "Orange"], size ["Small", "Medium", "Large"]
}
Edit: OP I've updated the code here and in the jsfiddle to show you how to loop over the new object to get the keys/values.
Fiddle.
var json = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var color = json['Option:Color'].split(',');
var size = json['Option:Size'].split(',');
Try this to do get a solution without hardcoding all the option names into your code:
var x = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var clean = {};
$.each(x, function(key, val){ //iterate over the options you have in your initial object
var optname = key.replace('Option:', ''); //remove the option marker
clean[optname] = val.split(","); //add an array to your object named like your option, splitted by comma
});
clean will contain the option arrays you want to create
EDIT: Okay, how you get the names of your object properties like "color", which are now the keys in your new object? Thats the same like before, basically:
$.each(clean, function(key, val){
//key is the name of your option here
//val is the array of properties for your option here
console.log(key, val);
});
Of course we stick to jQuery again. ;)

Hash Tables in javascript

I am trying to build a data structure.
In my limited knowledge, 'hash table' seems to be the way to go. If you think there is an easier way, please suggest it.
I have two, 1-dimensional arrays:-
A[] - contains names of badges (accomplishment)
B[] - contains respective dates those achievements were accomplished from array A[].
An achievement/accomplishment/badge can be accomplished more than one time.
Therefore a sample of the two arrays:-
A['scholar', 'contributor', 'teacher', 'student', 'tumbleweed', 'scholar'.....,'scholar',......]
B['1/2010', '2/2011', '3/2011', '6/2012', '10/2012', '2/2013',......'3/2013',........]
What I want to achieve with my data structure is:-
A list of unique keys (eq:- 'scholar') and all of its existing values (dates in array B[]).
Therefore my final result should be like:-
({'scholar': '1/2010', '2/2013', '3/2013'}), ({'contributor' : ........})..........
This way I can pick out a unique key and then traverse through all its unique values and then use them to plot on x-y grid. (y axis labels being unique badge names, and x axis being dates, sort of a timeline.)
Can anyone guide me how to build such a data structure??
and how do I access the keys from the data structure created.... granted that I don't know how many keys there are and what are their individual values. Assigning of these keys are dynamic, so the number and their names vary.
Your final object structure would look like this:
{
'scholar': [],
'contributor': []
}
To build this, iterate through the names array and build the final result as you go: if the final result contains the key, push the corresponding date on to its value otherwise set a new key to an array containing its corresponding date.
something like:
var resultVal = {};
for(var i = 0; i < names.length; ++i) {
if(resultVal[names[i]]) {
resultVal[names[i]].push(dates[i]);
} else {
resultVal[names[i]] = [dates[i]];
}
}
Accessing the result - iterating through all values:
for(var key in resultVal) {
var dates = resultVal[key];
for(var i = 0; i < dates.length; ++i) {
// you logic here for each date
console.log("resultVal[" + key + "] ==> " + resultVal[key][i]);
}
}
will give results like:
resultVal[scholar] ==> 1/2010
resultVal[scholar] ==> 2/2013
resultVal[scholar] ==> 3/2013
resultVal[contributor] ==> 2/2011
resultVal[teacher] ==> 3/2011
resultVal[student] ==> 6/2012
resultVal[tumbleweed] ==> 10/2012
You can try this...
var A = ['scholar', 'contributor',
'teacher', 'student', 'tumbleweed', 'scholar','scholar'];
var B = ['1/2010', '2/2011',
'3/2011', '6/2012', '10/2012', '2/2013','3/2013'];
var combined = {};
for(var i=0;i<A.length;i++) {
if(combined[A[i]] === undefined) {
combined[A[i]] = [];
}
combined[A[i]].push(B[i]);
}
Then each one of the arrays in combined can be accessed via
combined.scholar[0]
or
combined['scholar'][0]
Note the === when comparing against undefined

Ordered JSONObject

I have a servlet which talks with the database then returns a list of ordered (ORDER BY time) objects. At the servlet part, I have
//access DB, returns a list of User objects, ordered
ArrayList users = MySQLDatabaseManager.selectUsers();
//construct response
JSONObject jsonResponse = new JSONObject();
int key = 0;
for(User user:users){
log("Retrieve User " + user.toString());
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", user.getName());
jsonObj.put("time", user.getTime());
jsonResponse.put(key, jsonObj);
key++;
}
//write out
out.print(jsonResponse);
From the log I can see that the database returns User objects in the correct order.
At the front-end, I have
success: function(jsonObj){
var json = JSON.parse(jsonObj);
var id = 0;
$.each(json,function(i,item) {
var time = item.time;
var name = item.name;
id++;
$("table#usertable tr:last").after('<tr><td>' + id + '</td><td width="20%">' + time +
'</td><td>' + name +
'</td></tr>');
});
},
But the order is changed.
I only noticed this when the returned list has large size (over 130 users).
I have tried to debug using Firebug, the "response tab" in Firebug shows the order of the list is different with the log in the servlet.
Did i do anything wrong?
EDIT: Example
{"0":{"time":"2011-07-18 18:14:28","email":"xxx#gmail.com","origin":"origin-xxx","source":"xxx","target":"xxx","url":"xxx"},
"1":{"time":"2011-07-18 18:29:16","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"},
"2":
,...,
"143":{"time":"2011-08-09 09:57:27","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}
,...,
"134":{"time":"2011-08-05 06:02:57","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}}
As JSON objects do not inherently have an order, you should use an array within your JSON object to ensure order. As an example (based on your code):
jsonObj =
{ items:
[ { name: "Stack", time: "..." },
{ name: "Overflow", time: "..." },
{ name: "Rocks", time: "..." },
... ] };
This structure will ensure that your objects are inserted in the proper sequence.
Based on the JSON you have above, you could place the objects into an array and then sort the array.
var myArray = [];
var resultArray;
for (var j in jsonObj) {
myArray.push(j);
}
myArray = $.sort(myArray, function(a, b) { return parseInt(a) > parseInt(b); });
for (var i = 0; i < myArray.length; i++) {
resultArray.push(jsonObj[myArray[i]]);
}
//resultArray is now the elements in your jsonObj, properly sorted;
But maybe that's more complicated than you are looking for..
As mentioned by ghayes , json objects are unordered.
There are multiple solutions to this problem.
You can use array and the sort it to get the ordered list.
You can use gson library to get the desired order of elements.
I would prefer the second option as it is easy to use.
As JSONObject is order less and internally uses Hashmap. One way to use it to download the all classes from org.json and use in your project directly by changing the internal HashMap implementation to LinkedHashMap in JSONObject.java file. below is the sorted json files
https://github.com/abinash1/Sorted-Json-Object

Categories