Create JSON object with same keys for API call - javascript

I'm trying to create a JSON object for an API call which has the following format:
....
"Key": "Value",
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "20",
"Width": "25",
"Height": "30"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "80"
}
},
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "15",
"Width": "24",
"Height": "27"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "50"
}
},
"Key": "Value",
....
I should add as many "Package" objects as needed. However, I've tried doing this in many different ways but every time that I parse the variable to be used the first objects get overwritten and I end up with only the last object.
This is what I'm trying at the moment, still with no luck:
var lineItems = '{';
for (var i=0;i<inputObject.packages.length;i++) {
lineItems += '"Package": {"PackagingType": {"Code": "02","Description": "Rate"},"Dimensions": {"UnitOfMeasurement": {"Code": "IN","Description": "inches"},"Length": ' + inputObject.packages[i][0].toString() + ',"Width": ' + inputObject.packages[i][1].toString() + ',"Height": ' + inputObject.packages[i][2].toString() + '},"PackageWeight": {"UnitOfMeasurement": {"Code": "Lbs","Description": "pounds"},"Weight": ' + inputObject.packages[i][3].toString() + '}}';
if (i !== inputObject.packages.length-1) {
lineItems += ',';
}
}
lineItems += '}';
lineItems = JSON.parse(lineItems);

How about numbering your packages, ie:
for (var i=0;i<inputObject.packages.length;i++) {
lineItems+='"Package" + i : { ... }'
}
edit: to get required result (as an array - because it's not JSON), here's an example:
var a=[];
var b={"package": {"c":100,"d":200,"e":300}}
var c={"package": {"c":800,"d":700,"e":600}}
a.push(b);
a.push(c);
console.log(a);

Related

Javascript Push Product Info as Object to an Empty Array

I have an array of products would like to add all the product information as an object to an empty array.
var data = {
"Vegetables": [
{
"id": "1",
"title": "Peas",
"type": "Green",
},
{
"id": "2",
"title": "Carrots",
"type": "root",
}
],
"Protein": [
{
"id": "3",
"title": "Steak",
"type": "Meat",
},
{
"id": "4",
"title": "Eggs",
"type": "Dairy"
}
]}
I am able to push just the title to the empty result array with the following:
function getCategory() {
result = [];
for (let item in data) {
data[item].forEach(v => result.push(v.title));
}
document.write(result);
}
getCategory();
But I would like to be able to push all the product information as an object so I can do some formatting. For example:
var myObj= "" ;
myObj = "<div class='box'>" + title +"<br> "+ type + "</div>";
result.push(myObj); // push it to result[]
I am unsure how to adapt the body of the for loop to accommodate my object:
data[item].forEach(v => result.push(v.title + v.type)); // needs to be pushed as object.
Any help appreciated.
Cheers

Trying to pick data from a JSON response text

I'm trying to pick some data from my JSON response text which looks like this:
{
"status": "success",
"reservations": [
{
"id": "22959",
"subject": "SubjectName",
"modifiedDate": "2017-04-03T06:04:24",
"startDate": "2017-04-03T12:15:00",
"endDate": "2017-04-03T17:00:00",
"resources": [
{
"id": "17",
"type": "room",
"code": "codeName",
"parent": {
"id": "2",
"type": "building",
"code": "buildingName",
"name": ""
},
"name": ""
},
{
"id": "2658",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "2446",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "3137",
"type": "realization",
"code": "codeName",
"name": ""
},
{
"id": "3211",
"type": "realization",
"code": "codeName",
"name": "name"
}
],
"description": ""
},
{
"id": "22960",
"subject": "subjectName",
"modifiedDate": "2017-04-04T06:04:33",
"startDate": "2017-04-04T10:00:00",
"endDate": "2017-04-04T16:00:00",
"resources": [
{
"id": "17",
"type": "room",
"code": "codeName",
"parent": {
"id": "2",
"type": "building",
"code": "codeName",
"name": ""
},
"name": ""
},
{
"id": "2658",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "2446",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
}
],
"description": ""
}
]
}
I've been trying to use JSON.parse() and go through the response text with a for-loop with no success. I need to pick the subject names, room names, building names and both student_group names.
This is what my code currently looks like:
var getData = {
"startDate":,
"endDate":,
"studentGroup": [
""]
};
var data = new XMLHttpRequest();
data.onreadystatechange = function () {
if (data.readyState == 4 && data.status == 200) {
try {
// Parse JSON
var json = JSON.parse(data.responseText);
// for-loops
for (var i = 0; i < json.reservations.length; i++) {
for (var x = 0; x < json.reservations[i].length;
x++) {
document.getElementById("test").innerHTML =
json.reservations[i].subject;
}
}
} catch (err) {
console.log(err.message);
return;
}
}
};
// JSON query
data.open("POST", "URL", true, "APIKEY", "PASS");
data.setRequestHeader('Content-Type', 'application/json');
data.send(JSON.stringify(getData));
This only prints the last subject name if I have more than 1 of them.
How should I do this?
Once you have your data parsed, forget it once was JSON. Now you have a JavaScript object.
Check data.status to make sure everything went well.
Loop over data.reservations and, inside that, over data.reservations[i].resources.
You should treat your parsed data as an object, so to get you going, this will get all unique student group names from all returned resources:
var studentGroups = [];
for (var i = 0; i < json.reservations.length; i++) {
if(json.reservations[i].resources != null){
for(var j = 0; j < json.reservations[i].resources.length; j++){
var resource = json.reservations[i].resources[j];
if(resource.type === "student_group"){
if(studentGroups.indexOf("groupName"))
studentGroups.push(resource.name);
}
}
}
}
}
Of course I'm not sure in what format you want to get your result (should this be a flat array or maybe another JSON, maybe only first value is important for you?), but I think you should already have an idea how to handle the topic.

Reading JSON data and looping through it

I have 3 files
index.html
data.json
app.js
on my WAMP server. I wish to loop through the JSON data and update contents of the HTML file.
These are the contents of my files:
data.json
{
"user": [{
"goal": "HTML essential training",
"type": "Beginner",
"date": "20/07/2016"
}, {
"goal": "CSS essential training",
"type": "Beginner",
"date": "30/07/2016"
}, {
"goal": "CSS core concepts",
"type": "Intermediate",
"date": "10/08/2016"
}, {
"goal": "Javascript essential training",
"type": "Beginner",
"date": "20/08/2016"
}, {
"goal": "Object Oriented JS",
"type": "Advanced",
"date": "30/08/2016"
}]
}
app.js
var request = new XMLHttpRequest();
request.open('GET', 'data.json');
request.onreadystatechange = function() {
if ((request.readyState === 4) && (request.status === 200)) {
var items = JSON.parse(request.responseText);
console.log(items);
for (var key in items) {
console.log(key);
var output = "<tr><td><input type='checkbox' name='record'></td><td>" + items[key].goal + "</td><td>" + items[key].type + "</td><td>" + items[key].date + "</td></tr>";
console.log(output);
$("table tbody").append(output);
output = '';
}
}
}
request.send();
When i run this code, one row is created with all the values set to undefined. I think there's a problem with my looping logic.Please help me.
You are running into this since the object returned is a single key: value pair.
You need to access the user property which is an array.
your code
var items=JSON.parse(request.responseText);
The value you get after parsing the json string is the javascript object with key : 'user' and value : which is an array
Supposed to be
var data =JSON.parse(request.responseText);
var items = data.user; <-- this is an array of objects
// iterate using a for loop, since it is not an object technically
for(var i=0; i < items.length; i++) {
Take a look at the structure of your object:
{
"user": [
{
"goal": "HTML essential training",
"type": "Beginner",
"date": "20\/07\/2016"
},
{
"goal": "CSS essential training",
"type": "Beginner",
"date": "30\/07\/2016"
},
{
"goal": "CSS core concepts",
"type": "Intermediate",
"date": "10\/08\/2016"
},
{
"goal": "Javascript essential training",
"type": "Beginner",
"date": "20\/08\/2016"
},
{
"goal": "Object Oriented JS",
"type": "Advanced",
"date": "30\/08\/2016"
}
]
}
There's one key, with the value being an array.
You need a loop like this:
for (var key in items){if (items.hasOwnProperty(key)) {
for (var i in items[key]) {if (items[key].hasOwnProperty(i)){
console.log(items[key][i]);
var output="<tr><td><input type='checkbox' name='record'></td><td>" + items[key][i].goal + "</td><td>" + items[key][i].type + "</td><td>" + items[key][i].date + "</td></tr>";
console.log(output);
$("table tbody").append(output);
output='';
}}
}}

How to loop through properties of a JSON object?

I am trying to loop through the properties of JSON object, but unable to do so.
var ds={
"Table": [
{
"SrNo": 1,
"AuctionName": "test auction",
"AuctionDescription": "auction desc",
"Testproject": "Y",
"State": "India",
"City": "2",
"CompanyName": "IIFL",
"Commodity": "10001",
"BaseLineSpend": "50000",
"ContractMonths": "5",
"Owner": "arbaaz",
"PreviewBids": "Y",
"PrebidEndTime": "2015-09-11T18:00:00",
"BiddingStartTime": "2015-09-10T18:00:00",
"FirstTimeRunTime": 10,
"TimeBtwLotClosing": 15,
"BidRank": "20",
"StartOverTime": 25,
"OverTime": 30,
"Buffer": "Y",
"ImproveBidBy": "PERCENTAGE",
"TieBids": "Y",
"ActiveObservers": "Babitha G-C140492,",
"Observers": "Tabrez Abdul Aziz Shaikh-A185615,",
"ProjectOwner": "Tahir - Siddiqui-C107037,Tahir Ali-C132420,",
"Administrator": "Rabi Roy-V182597,Gagan Kondalana Poonacha-C134452,Rabindra Kumar Choubey-C139454,",
"GUID": "200869b0-e6be-4642-95ec-97509e457d63",
"MkrId": "C123627",
"MkrDt": "2015-09-03T16:23:15.917",
"IsCreated": null
}
]
}
Based on other similar question on stackoverflow. I tried:
var DataSet = jQuery.parseJSON(ds);
var json_parsed = DataSet.Table;
var items = json_parsed.Items; // this is always undefined in console.
for (var i = 0; i < items.length; ++i) {
console.log("Item #" + i);
for (var name in items[i]) {
alert(name + "=" + items[i][name]);
}
}
I get undefined at json_parsed.Items; in console.
I am expecting property names to be displayed in alert eg: Srno, AuctionName .. so on.
Well, Table is an array, for a start. Second, even if you used Table[0].Items, there's no Items property, which is why you're getting "undefined".
So try this instead:
var items = json_parsed[0];
for (var name in items) {
alert(name + "=" + items[name]);
}
DEMO
I see you have jQuery in there. The Javascript approach is good. But if you want to loop through a JSON object in jQuery, then you can try following code:
var ds={
"Table": [
{
"SrNo": 1,
"AuctionName": "test auction",
"AuctionDescription": "auction desc",
"Testproject": "Y",
"State": "India",
"City": "2",
"CompanyName": "IIFL",
"Commodity": "10001",
"BaseLineSpend": "50000",
"ContractMonths": "5",
"Owner": "arbaaz",
"PreviewBids": "Y",
"PrebidEndTime": "2015-09-11T18:00:00",
"BiddingStartTime": "2015-09-10T18:00:00",
"FirstTimeRunTime": 10,
"TimeBtwLotClosing": 15,
"BidRank": "20",
"StartOverTime": 25,
"OverTime": 30,
"Buffer": "Y",
"ImproveBidBy": "PERCENTAGE",
"TieBids": "Y",
"ActiveObservers": "Babitha G-C140492,",
"Observers": "Tabrez Abdul Aziz Shaikh-A185615,",
"ProjectOwner": "Tahir - Siddiqui-C107037,Tahir Ali-C132420,",
"Administrator": "Rabi Roy-V182597,Gagan Kondalana Poonacha-C134452,Rabindra Kumar Choubey-C139454,",
"GUID": "200869b0-e6be-4642-95ec-97509e457d63",
"MkrId": "C123627",
"MkrDt": "2015-09-03T16:23:15.917",
"IsCreated": null
}
]
}
var jsonData = ds.Table[0];
$.each(jsonData, function(index, value) {
console.log( index + '=' + value);
});

drill down through json data

Im experimenting with the espn public API and am trying to use their json to access NFL player information.
the json im accessing succesfully looks like:
{
"sports": [
{
"name": "football",
"id": 20,
"leagues": [
{
"name": "National Football League",
"abbreviation": "nfl",
"id": 28,
"groupId": 9,
"shortName": "NFL",
"athletes": [
{
"id": 14466,
"firstName": "Isa",
"lastName": "Abdul-Quddus",
"fullName": "Isa Abdul-Quddus",
"displayName": "Isa Abdul-Quddus",
"shortName": "I. Abdul-Quddus",
"links": {
"api": {
"athletes": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/14466"
},
"news": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/14466/news"
},
"notes": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/14466/news/notes"
}
},
"web": {
"athletes": {
"href": "http://espn.go.com/nfl/player/_/id/14466/isa-abdul-quddus?ex_cid=espnapi_public"
}
},
"mobile": {
"athletes": {
"href": "http://m.espn.go.com/nfl/playercard?playerId=14466&ex_cid=espnapi_public"
}
}
}
},
{
"id": 8645,
"firstName": "Hamza",
"lastName": "Abdullah",
"fullName": "Hamza Abdullah",
"displayName": "Hamza Abdullah",
"shortName": "H. Abdullah",
"links": {
"api": {
"athletes": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/8645"
},
"news": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/8645/news"
},
"notes": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/8645/news/notes"
}
},
"web": {
"athletes": {
"href": "http://espn.go.com/nfl/player/_/id/8645/hamza-abdullah?ex_cid=espnapi_public"
}
},
"mobile": {
"athletes": {
"href": "http://m.espn.go.com/nfl/playercard?playerId=8645&ex_cid=espnapi_public"
}
}
}
},
{
"id": 11910,
"firstName": "Husain",
"lastName": "Abdullah",
"fullName": "Husain Abdullah",
"displayName": "Husain Abdullah",
"shortName": "H. Abdullah",
"links": {
"api": {
"athletes": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/11910"
},
"news": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/11910/news"
},
"notes": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/11910/news/notes"
}
} ........
]
}
]
}
],
"resultsOffset": 0,
"resultsLimit": 50,
"resultsCount": 3301,
"timestamp": "2013-01-06T19:30:17Z",
"status": "success"
}
and heres the html / javascript Im using:
$(document).ready(function(){
$.getJSON("http://api.espn.com/v1/sports/football/nfl/athletes?apikey=MY-API-KEY-HERE&_accept=application/json",
function(data){
$.each(data["sports"], function(i,item){
$("#infoDiv").append( [i] + " - " + item.name + "<br>" );
});
});
});
i can get this to display 0 - football but cant use something like
$.each(data["sports"]["leagues"]["athletes"], function(i,item){
$("#infoDiv").append( [i] + " - " + item.firstName + "<br>" );
to access the individual athlete data such as item.firstName , etc.
i keep getting the following error:
TypeError: data.sports.leagues is undefined
what am I missing? I'm using this same code structure successfully with a couple of other API's that provide json. the ESPN json is a little more complex in comparison though.
thanks for any light you can shed on this for me.
sports, leagues and athletes are arrays, for example: sports[0] is an object (the one with name='football')
You should iterate each like this (not tested):
$.each(data.sports, function(i,sport) {
$.each(sport.leagues, function(i,league) {
$.each(league.athletes, function(i,athlete) {
$("#infoDiv").append( [i] + " - " + athlete.firstName + "<br>" );
});
});
});
sports, leagues and athletes are arrays which you need to iterate.
for (var i=0; i<data.sports.length; i++) {
var sport = data.sports[i];
$("#infoDiv").append( [i] + " - " + sport.name + "<br>" );
for (var j=0; j<sport.leagues.length; j++) {
var league = sport.leagues[j];
$("#infoDiv").append( [i,j] + " - " + league.name + "<br>" );
for (var k=0; k<league.athletes.length; k++) {
var athlete = league.athletes[k];
$("#infoDiv").append( [i,j,k] + " - " + athlete.fullName + "<br>" );
}
}
}

Categories