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>
});
});
Related
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"
}
]
}
};
I am newbie to JSON, I am parsing a JSON Object and i was struck at a point where i have to read the array Elements inside a Object, that is again in another array..
Here is MY JSON
{
"DefinitionSource": "test",
"RelatedTopics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/a5e4a93a.jpg"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Result": "",
"Icon": {
"URL": "xyz"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Topics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/10d02dbf.jpg"
},
"FirstURL": "https://duckduckgo.com/Snake_Indians",
"Text": "sample"
},
{
"Result": "sample",
"Icon": {
"URL": "https://duckduckgo.com/i/1b0e4eb5.jpg"
},
"FirstURL": "www.google.com",
"Text": "xyz."
}
]
}
]
}
Here I need to read URL ,FIRSTURL and Text from RelatedTopics array and Topics array..
Can anyone help me. Thanks in advance.
Something like this
function (json) {
json.RelatedTopics.forEach(function (element) {
var url = element.Icon ? element.Icon.URL : 'no defined';
var firstURL = element.FirstURL ? element.FirstURL : 'no defined';
var text = element.Text ? element.Text : 'no defined';
alert("URL: " + url + "\nFirstURL: " + firstURL + "\nText: " + text);
if (element.Topics)
{
element.Topics.forEach(function (topicElement) {
alert("Topics - \n" + "URL: " + topicElement.Icon.URL + "\nFirstURL: " + topicElement.FirstURL + "\nText: " + topicElement.Text);
});
}
});
};
Look fiddle example
Loop through json Array like,
for(var i=0; i< RelatedTopics.length;i++){
if($.isArray(RelatedTopics[i])){
for(var j=0; j< RelatedTopics[i].Topics.length;j++){
var topics=RelatedTopics[i].Topics[j];
var text = topics.Text;
var firsturl = topics.Firsturl;
var url = topics.Icon.url;
}
}
}
if you want push it an array variable
I'm working with results from the Facebook Javascript SDK, and the "attachments" part of the object is giving me trouble. When looking at the object it's all good, but when I try to display it on my website, it says these properties are undefined. Am I parsing incorrectly?
Here's the object:
{
"id":"xxx_xxx",
"from":{
"id":"xxxx",
"name":"User Name"
},
"to":{
"data":[{
"name":"Group Name",
"id":"xxxx"
}]
},
"picture":"url of image",
"link":"url",
"object_id":"Object ID",
"type":"photo",
"created_time":"2014-10-15T21:09:19+0000",
"updated_time":"2014-10-15T21:09:19+0000",
"attachments":{
"data":[{
"media":{
"image":{
"height":551,
"src":"Image Source",
"width":720
}
},
"target":{
"id":"742450405803347",
"url":"target URL"
},
"type":"photo",
"url":"URL"
}]
}
And here's the code to display the "attachments" part on the website (I know it's messy, please ignore that):
post_div_html += '<p>------------------</p>\
<p><b>Media-Image-Source</b>: ' + feed.attachments.data[0] + '</p>\
<p><b>Target URL</b>: ' + feed.attachments.data[1] + '</p>\
<p><b>Type</b>: ' + feed.attachments.data[2] + '</p>\
<p><b>URL</b>: ' + feed.attachments.data[3] + '</p></div>';
Now, just to be clear, what you see there results in 'undefined' being displayed as the value on my website. Everything else I have tried has resulted in an error saying that 'feed.attachments.data.whatever is undefined'.
Anyone have any ideas on how I need to be displaying this stuff?
I think what you want is...
var att = feed.attachments.data[0],
mediaImageSrc = att.media.image.src,
targetUrl = att.target.url,
type = att.type,
url = att.url;
I hope that makes sense.
Here's a working example...
var feed = {
"id": "xxx_xxx",
"from": {
"id": "xxxx",
"name": "User Name"
},
"to": {
"data": [{
"name": "Group Name",
"id": "xxxx"
}]
},
"picture": "url of image",
"link": "url",
"object_id": "Object ID",
"type": "photo",
"created_time": "2014-10-15T21:09:19+0000",
"updated_time": "2014-10-15T21:09:19+0000",
"attachments": {
"data": [{
"media": {
"image": {
"height": 551,
"src": "Image Source",
"width": 720
}
},
"target": {
"id": "742450405803347",
"url": "target URL"
},
"type": "photo",
"url": "URL"
}]
}
};
var att = feed.attachments.data[0],
mediaImageSrc = att.media.image.src,
targetUrl = att.target.url,
type = att.type,
url = att.url;
post_div_html = '<p>------------------</p>\
<p><b>Media-Image-Source</b>: ' + mediaImageSrc + '</p>\
<p><b>Target URL</b>: ' + targetUrl + '</p>\
<p><b>Type</b>: ' + type + '</p>\
<p><b>URL</b>: ' + url + '</p></div>';
document.getElementById('out').innerHTML = post_div_html;
<output id="out"></output>
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"
}
}
I am working with an API that is returning data in JSON format. An example of a response is this
{
"code": 200,
"count": 4,
"currentPage": 1,
"date": "2013-05-24T09:19:37.964+1000",
"executedQuery": "cafe",
"message": "OK",
"originalQuery": "cafe",
"results": [{
"aboutId": "b3ec5ac4096078f89fa4a9f3adcec930a1d4997c7cae30b026d61f8fcbf2013b",
"categories": [{
"id": "35491",
"name": "Cafes",
"sensitive": false
}],
"detailsLink": "http://www.yellowpages.com.au/nsw/mt-colah/bobbin-inn-13830124-listing.html?referredBy=TAPI-jHOsyHrSfHBBlo0IExDjXZZJx6PszwX6",
"hasExposureProducts": false,
"id": "13830124",
"listingType": "Business",
"name": "Bobbin Inn",
"primaryAddress": {
"addressLine": "1 Chase Rd",
"geoCodeGranularity": "PROPERTY",
"latitude": "-33.678276",
"longitude": "151.112964",
"mappable": true,
"postcode": "2079",
"state": "NSW",
"suburb": "Mt Colah",
"type": "PHYSICAL"
},
"primaryContacts": [{
"type": "PHONE",
"value": "(02) 9457 7170"
}],
"pureMobileBusiness": false,
…
From what i can tell there is a number of arrays in this response. I am failing however to parse this data on a create method
here is my code (this is working for this field i have defined but ... see below)
for (var i in p) {
str += blocka + uibare + p.executedQuery + " (" + p.executedQuery+ ")</div></div>";
str += blockb + uibarc + p.executedQuery + "</div></div>";
str += blockc + uibare + p.executedQuery + "</div></div>";
str += blockd + uibarc + p.executedQuery + "</div></div>";
str += blocke + uibare + p.executedQuery + "</div></div>";
}
This is working, because executedQuery is not part of the array. However if i want to get for example the "name" that appears to be part of the results array? Or am i reading it wrong?
so i tried
str += blockb + uibarc + p.results[i].name + "</div></div>";
and it won't pull any data.
results is an array that contains a single object of keys and values.
Try result[0]["name"].
More suitable to your request:
str += blockb + uibarc + p.results[0]["name"] + "</div></div>";