How to iterate json data in jquery + ajax - javascript

But i get respnce in json, i.e alert(html)
<script>
function addcartAction(id){
var dataString='id='+id;
$.ajax({
type: "POST",
url:"<?php echo Yii::app()->request->baseUrl; ?>/testurl",
data: dataString,
success: function(html)
{
alert(html);
$("#cart-item").html(html);
}
});
}
</script>
{
"1": {
"ItemName": "Product1",
"id": "1",
"item_Image": "http://testurl.com/gallerythumb/test.JPG",
"price": "4.99",
"quantity": 1
},
"2": {
"ItemName": "Product2",
"id": "2",
"item_Image": "http://testurl.com/gallerythumb/test1.jpg",
"price": "7.99",
"quantity": 12
}
}
I have tried alot of different syntax but can't seem to figure this out.
Can any one point me in the right direction?, so can i solve this one.

Once you have your json string, use the parseJSON() function, which returns an object. Then you can access it's properties as shown in the docs.
Also you might refer to:
Converting JSON Object into Javascript array
Convert JSON string to Javascript array

You can use $.each to iterate JavaScript object
var data = {
"1": {
"ItemName": "Product1",
"id": "1",
"item_Image": "http://testurl.com/gallerythumb/test.JPG",
"price": "4.99",
"quantity": 1
},
"2": {
"ItemName": "Product2",
"id": "2",
"item_Image": "http://testurl.com/gallerythumb/test1.jpg",
"price": "7.99",
"quantity": 12
}
};
$.each(data,function(i, v) {
console.log(i);
$.each(v,function( ind , val) {
console.log( ind , val);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

You need to look at loading JSON data using an HTTP GET request (you can also use POST).
JSON jQuery Syntax:
jQuery.getJSON( url, [ data ], [ success(data, textStatus, jqXHR) ] );
url – A string containing the URL to which the request is sent.
data – A map or string that is sent to the server with the request.
success(data, textStatus, jqXHR) – A callback function that is executed if the request succeeds.
Download Example
Code reference here.

Something like this!
var data={
"1": {
"ItemName": "Product1",
"id": "1",
"item_Image": "http://testurl.com/gallerythumb/test.JPG",
"price": "4.99",
"quantity": 1
},
"2": {
"ItemName": "Product2",
"id": "2",
"item_Image": "http://testurl.com/gallerythumb/test1.jpg",
"price": "7.99",
"quantity": 12
}
};
$.each(data,function(key,value){
var element='<div class="elem">Item No : '+key+
' <span>Item Name : '+value.ItemName+'</span> '+
' <span>Id : '+value.id+'</span> '+
' <img src="'+value.item_Image+'"/> '+
' <span>Price: '+value.price+'</span> '+
' <span>Quantity : '+value.quantity+'</span></div> ';
$('body').append(element);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Update
Say you have following ajax
$.ajax({
url:'someurl',
type:'POST',
dataType:'json',
success: function(data)
{
$.each(data,function(key,value){
var element='<div class="elem">Item No : '+key+
' <span>Item Name : '+value.ItemName+'</span> '+
' <span>Id : '+value.id+'</span> '+
' <img src="'+value.item_Image+'"/> '+
' <span>Price: '+value.price+'</span> '+
' <span>Quantity : '+value.quantity+'</span></div> ';
$('body').append(element); //append it to anywhere in DOM using selector
});
},
error:function(jqXHR,responseData,status){
//do something
}
});

Related

Loop through a nested JSON object to find a value id

"results": {
"data": {
"facets": {
"60749428": {
"id": 60749428,
"name": "KC Content Content Kind"
},
"60750276": {
"id": 60750276,
"name": "KC Content Product Version"
},
"69107204": {
"id": 69107204,
"name": "KC Video Audience"
},
"69127027": {
"id": 69127027,
"name": "KC Content Kind ID"
}
}
}
}
I want to loop through this nested json object by going into the facet object and say if the name attribute is "KC Content Kind ID" then return the id for that corresponding name attribute
So after getting my api call with postman I was trying to get the corresponding id of the "KC Content Kind ID" in my success function this way, but since its not an array I was wondering if each will work in jquery.
//Get Available Kinds
function getAvailableKinds() {
$.ajax({
url: csexe + "/api/v2/facets/" +getLocationId(),
dataType: "json",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader ("OTCSticket", getAuthToken());
},
success: function(response) {
var obj = response.results.data.facets;
$.each(obj, function(item, value){
if ( value == 'KC Content Kind ID') {
var idRequired = obj.id;
}
});
},
error: function(jqXHR, textStatus, errorThrown){
alert("An error occurred... Look at the console");
$("body").html('<p>status code: '+jqXHR.status+'</p><p>Error Thrown: ' + errorThrown + '</p><p>Response Text:</p><div>'+jqXHR.responseText + '</div>');
}
});
Just parse the string over and then do a simple loop.
var jsonObj = (JSON.parse("your json here")).data.facets;
for (i = 0; i<jsonObj.length;i++)
{
if(jsonObj[i].name == "KC Content Kind ID")
return jsobObj[i].id;
}
you can use Object.keys and find
const obj = {"results": {"data": {"facets": {"60749428": {"id": 60749428,"name": "KC Content Content Kind"},"60750276": {"id": 60750276,"name": "KC Content Product Version"},"69107204": {"id": 69107204,"name": "KC Video Audience"},"69127027": {"id": 69127027,"name": "KC Content Kind ID"}}}}};
const facets = obj.results.data.facets;
const result = Object.keys(facets).find(v => facets[v].name === 'KC Content Kind ID');
//your object keys are equal to id, you can just return key
console.log(result);
// if your object keys can be different from id you can do this
console.log(facets[result].id);
I think the easiest way to achieve this would be by using Object.values function in conjunction with Array.prototype.filter. You can then take the first item from the array returned by the filter method (since each ID should be unique) and display it's ID.
const o = { "results": { "data": { "facets": { "60749428": { "id": 60749428, "name": "KC Content Content Kind" }, "60750276": { "id": 60750276, "name": "KC Content Product Version" }, "69107204": { "id": 69107204, "name": "KC Video Audience" }, "69127027": { "id": 69127027, "name": "KC Content Kind ID"}}}}};
const [a] = Object.values(o.results.data.facets).filter(f => f.name == "KC Content Kind ID");
console.log(a.id);
var obj = {
"results": {
"data": {
"facets": {
"60749428": {
"id": 60749428,
"name": "KC Content Content Kind"
},
"60750276": {
"id": 60750276,
"name": "KC Content Product Version"
},
"69107204": {
"id": 69107204,
"name": "KC Video Audience"
},
"69127027": {
"id": 69127027,
"name": "KC Content Kind ID"
}
}
}
}
};
let facets = obj.results.data.facets;
let id;
for(let key in facets){
if(facets[key].name == 'KC Content Kind ID'){
id = facets[key].id;
break;
}
}
console.log(id);

How to parse nested jsonp objects using javascript?

I have a valid jsonp as follows . I am trying to parse it but i don't know how to access videos elements! Could any one tell me how to reference those elements(sources,thumb,title) inside for loop ?Thanks
valid jsonp:
{
"categories": [{
"name": "october list",
"videos": [{
"sources": [
"http://www.somesite.com.com/test.m3u8"
],
"thumb": "http://www.somesite.com.com/1.jpg",
"title": "title of test",
"subtitle": "",
"description": ""
}, {
"sources": [
"http://www.somesite.com/test2.m3u8"
],
"thumb": "http://www.somesite.com/2.jpg",
"title": "test2",
"subtitle": "",
"description": ""
}
]
}]
}
javascript:
$.get("http://www.someapisite.com/test.php",
{
dataType: "jsonp"
},
function(data,status){
var json = $.parseJSON(data);
// then loop the single items
for(i in json)
{
// create HTML code
var div = "<div class=\"image\">\n" +
"<a href=\"javascript:dofunction('./test.php?title=" + json[i].title + "&TargetUrl=http://somesite.com/" + json[i].sources + "')\">\n" +
"<img src=\""+ json[i].thumb +"\" alt=\"..\" />\n" +
"</a>\n" +
"</div>\n";
// append it inside <body> tag.
$("#myDiv").append(div);
}
});
It seems you want to iterate over the videos array for each category.
Using javascript forEach
json.categories.forEach(function(category, index, array) {
category.videos.forEach(function(videoDetail, index, array) {
<img src=\"" videoDetail.thumb \"" />
<h3>videoDetail.title</h3>
});
});

JSON nested Parsing Help using $.each

Below is sample JSON response. I need to parse this in a generic way instead of using transactionList.transaction[0].
"rateType": interestonly,
"relationshipId": consumer,
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
},
I am using the following code to parse json
$.each(jsonDataArr, recursive);
function recursive(key, val) {
if (val instanceof Object) {
list += "<tr><td colspan='2'>";
list += key + "</td></tr>";
$.each(val, recursive);
} else {
if(val != null) {
if(!val.hasOwnProperty(key)) {
list += "<tr><td>" + key + "</td><td>" + val + "</td></tr>";
}
}
}
}
and this outputs as transactionList
transaction
0 and then the other keys & values. I was hoping to get transactionList and all the keys and values instead of getting the transaction and the array element. So I guess my parsing logic is not correct. Can anyone help me address this so I can just have the transactionList displayed? Thanks for your help inadvance.
It would help if we had an example of your desired results.
What if there are multiple transactions in the transactionList, how would it be displayed?
Essentially your issue is that Arrays are Objects as well.
http://jsfiddle.net/v0gcroou/
if (transactionList.transaction instanceof Object) == true
Key of transactionList.transaction is 0
Instead you need to also test if the object is an array, and do something else based on the fact you're now parsing an array instead of a string or JSON object
(Object.prototype.toString.call(val) === '[object Array]')
Another easy way would be to check the 'number' === typeof key since your JSON object does not contain numeric keys, but array objects inherently do.
http://jsfiddle.net/h66tsm9u/
Looks like you want to display a table with all your data. I added border=1 to the tables to visualize the boxes. See an example in http://output.jsbin.com/wuwoga/7/embed?js,output
function display(data) {
var html = "<table border='1'>";
var lists = recursive(data);
html += lists + "</table>";
return html;
}
function recursive(json) {
var list = "";
var instanceObj = false;
$.each(json, function(key, val){
instanceObj = (val instanceof Object);
list += [
"<tr>",
"<td>" + key + "</td>",
(instanceObj) ?
"<td><table border='1'>" + recursive(val) + "</table></td>" :
"<td>" + val + "</td>",
"</tr>"
].join("");
});
return list;
}
If you call display(json) with the json below, you'd get a display of all your data. If you add more data in the transaction array, it will display that too
var json = {
"rateType": "interestonly",
"relationshipId": "consumer",
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
}
};

WoW Armory APi - Can't get Title

Hello I'm trying to pull my characters title from the Warcraft Armory but I don't get any returned results. My code is as follows with my character name being replaced with my actual character name .
HTML
<li>Title Prefix: <span id="title">Test</span>
Javascript
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
});
}
);
function GoGet(data) {
$("#title").html(data.titles.name)
;}
The api documentation shows the json items for "titles" as follows:
{
"achievementPoints": 675,
"battlegroup": "Test Battlegroup",
"calcClass": "f",
"class": 10,
"gender": 1,
"lastModified": 1348187981118,
"level": 90,
"name": "Peratryn",
"race": 25,
"realm": "Test Realm",
"thumbnail": "test-realm/1/1-avatar.jpg",
"titles": [
{
"id": 285,
"name": "%s, Savior of Azeroth",
"selected": true
}
]
}
Where am I going wrong?
Not being a WOW player myself, I'll hazard one guess:
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
success: UpdateTitle
});
}
);
function UpdateTitle(response) {
if (response.titles) {
for (var i = 0; i < response.titles.length; i++) {
if (response.titles[i].selected === true) {
$("#title").html(response.titles[i].name);
break;
}
}
}
}
What this is doing is calling UpdateTitle after a successful XHR response from your provided URL. This function will loop through each title and update your #title element with the FIRST selected: true title found in the json response.

Get Child JSON Values from Objects

I have an endpoint with two JSON Objects as follows:
{
"main" {
"id": 1,
"title": Main Title,
},
{
"secondary" {
"id": 3,
"title": Secondary Title,
},
I am using backbone and have the following $each function, but using dot notation, I can't seem to be able to browse to the titles (ex. main.title or secondary.title). What am I missing?
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
$.each(response, function (index, value) {
console.log(value.main.title);
$("#test2").append('<li>' + value.main.title + '</li>');
});
In my console, it gives an error of: Uncaught TypeError: Cannot read property 'title' of undefined
Assuming your JSON is actually valid when returned (it isn't valid the way you show it), try
$("#test2").append('<li>' + value.title + '</li>');
Your actual JSON should look like:
{
"main": {
"id": 1,
"title": Main Title,
},
"secondary": {
"id": 3,
"title": Secondary Title,
}
}
If you just want the value of main, instead of using $.each(), remove that entire block and do:
$("#test2").append('<li>' + response.main.title + '</li>');
And your final code would look something like:
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
if (response.main.title !== 'undefined'){
$("#test2").append('<li>' + value.main.title + '</li>');
}else{
console.log('Main is undefined');
}
}
});
Final Edit: It looks like you want JSON like:
{
"main": [{
"id": 1,
"title": "Main Title"
}, {
"id": 2,
"title": "Main Title 2"
}, {
"id": 3,
"title": "Main Title 3"
}],
"secondary": [{
"id": 5,
"title": "Secondary Title 5"
}, {
"id": 34,
"title": "Secondary Title 34"
}, {
"id": 36,
"title": "Secondary Title 36"
}]
}
If that is the case your code would look like:
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
$.each(function(index, value){
$.each(item_index, item_value){
$("#test2").append('<li>' + item_value.title + '</li>');
}
});
}
});
The problem lies with input JSON, it should be
{
"main" :{
"id": 1,
"title": "Main Title"
},
"secondary":{
"id": 3,
"title": "Secondary Title"
}
}

Categories

Resources