How to read array inside JSON Object this is inside another array - javascript

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

Related

How to loop through jason data and display it in data list tag (dl)

I'm trying to loop through some JSON data (var mydata) and mydata is an array of two elements, the second element in the array
mydata[1] is a multidimensional array, I need to display the first element i.e mydata[0] in a dt and display elements from mydata[1] in a dd within that.
I tried every option but I'm really stuck and I need any help on this. Below is my code:
var mydata = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
function getCategories(id){
$.ajax({
url: '{$getcatUrl}',
type: 'POST',
data: {category_id: id},
success: function (data) {
data = jQuery.parseJSON(data);
//console.log(data); return;
if(data.length > 0){
firstdata = data[0];
secdata = data[1];
for(var i = 0; i < firstdata.length; i++) {
level_1 = firstdata[i].name;
level_1_id = firstdata[i].id;
for(var j = 0; j< secdata.length; j++){
if(secdata[i][j] !== undefined){
level_2='';
level_2 = secdata[i][j].name;
level_2_id = secdata[i][j].d;
}
console.log(level_2);
}
var dldata = $(
'<dl>'+
"<dt href='" + level_1_id + "'>" + level_1 + "</dt>"+
"<dd href='" + level_2_id + "'>" + level_2 + "</dd>"+
'</dl>'
);
}
}else{
console.log('no item for this categories');
}
},
error: function(jqXHR, errMsg) {
// handle error
console.log(errMsg);
}
});
}
The var level_1 and level_1_id works fine, but i keep getting error for variable level_2, the error says can't read property 'name' of undefined, any solution to this problem will be appreciated and am also open to new ideas about doing it better,
Essentially the problem is that you overwrite the level_1 and level_2 variables each time your for loops run. So by the time you get to the code which makes the HTML, they have been overwritten multiple times and only the last version remains, and you only print that once in any case.
This will resolve it - in this case by generating the HTML elements directly within each loop, although you could of course do it by appending to a variable and then outputting everything at the end, if that's your preference.
var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
if (data.length > 0) {
var content = $("#content");
firstdata = data[0];
secdata = data[1];
for (var i = 0; i < firstdata.length; i++) {
var dl = $("#content").append("<dl/>");
dl.append("<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dd>");
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
dl.append("<dd href='" + secdata[i][j].id + "'>" + secdata[i][j].name + "</dd>");
}
}
}
content.append(dl);
} else {
console.log('no item for this categories');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>

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>
});
});

Formatting JSON for email body

I've JSON in the following format that I'm trying to insert into outlook/email client's body using
location.href = "mailto:" + "email#domain.com" + "?subject=" + "Notes" + "&body=" + JSON.stringify(data, null, 4);
Giving 4 spaces JSON.stringify(data, null, 4)
[
{
"page": "article_0_page_0",
"note": "Note 1"
},
{
"page": "article_0_page_1",
"note": "Note 2"
}
]
I want to output as
<b>article_0_page_0</b>\n\r
Note 1
<b>article_0_page_1</b>\n\r
Note 2
Any regular expression solution please.
Edit: My attempt
var str = "";
for(var i=0; i<data.length; i++) {
str += "<strong>" + data[i].page + "</strong><br>" + data[i].note + "<br><br>";
}
I think the above answer is ok if you have a flat structure.
If you want a more holistic approach for email specifically, I have found this to work really well.
const data = {...}
JSON.stringify( data, null, ' ' ).split( '\n' ).join( '<br>' );
This will convert something like this
const json = {
"status": "ok",
"config": {
"gotIt": "yes",
"transform": [
null
]
}
}
Into something like this
{<br>&nbsp"status": "ok",<br>&nbsp"config": {<br>&nbsp&nbsp"gotIt": "yes",<br>&nbsp&nbsp"transform": [<br>&nbsp&nbsp&nbspnull<br>&nbsp&nbsp]<br>&nbsp}<br>}
Email clients will render this as the following
{
"status": "ok",
"config": {
"gotIt": "yes",
"transform": [
null
]
}
}
This is done by using the additional parameters in JSON.stringify which I don't see used very often if you want to read more about these parameters here is the link for them.
Here ya go
var json = [
{
"page": "article_0_page_0",
"note": "Note 1"
},
{
"page": "article_0_page_1",
"note": "Note 2"
}
];
var out = "";
for (var key in json) {
if (json.hasOwnProperty(key)) {
out += "<b>"+json[key].page+"</b>\r\n"+json[key].note+"\r\n\r\n";
}
}
console.log(out);
Example Here: https://jsfiddle.net/q5r4gdcn/1/
This is what I used to convert basic JSON to "readable" for email:
let json = {
"key": "asdas",
"query": "",
"hints": {
"nested1": "blahblah"
}
}
let prettyJSON = JSON.stringify(json, null, ' ')
.split('\n')
.join('<br> ')
.split('<br> }').join('<br>}')
document.body.innerHTML += `<div>${prettyJSON}</div>`

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"
}
]
}
};

Getting complex attribute value of object

Given json like this :
{ "rss": {
"page": 1,
"results": [{
"type": "text",
"$": 10
}],
"text": [{
"content": "Lorem ipsum dolor sit amet.",
"author": {
"name": "Cesar",
"email": "cesar#evoria.com"
},
},
{
"content": "Tema Tis rolod muspi merol.",
"author": {
"name": "Cleopatre",
"email": "cleopatre#pyramid.com"
},
}]
}
In javascript, I can retrieve value like this :
var json = JSON.parse(datajson);
$.each(json.text, function(key, val) {
// this one is ok
var content = val['content'];
// this one does not work
var authorname = val['author.name'];
});
Is this a way, given the attribute name in a string format, to retrieve the value of a complex object, for instance json.text[0].author.name?
EDIT
I would like to store the needed attributes in another object like :
[
{ dt: "Text content", dd: "content" },
{ dt: "Author name", dd: "author.name"}
]
You can split your "index" by . and loop over "segments", descending through levels on each iteration.
var obj = {
author : {
name : "AuthorName"
}
}
function get_deep_index(obj, index) {
var segments = index.split('.')
var segments_len = segments.length
var currently_at = obj
for(var idx = 0; idx < segments_len; idx++) {
currently_at = currently_at[segments[idx]]
}
return currently_at
}
console.log(get_deep_index(obj, 'author.name'))
The following should fix the problem.
var authorname = val['author']['name'];
You can also store the object itself as:
var author = val['author'];
And then later on you can index the attributes from that.
console.log(author.name, author.email)
Yent give a good hint in the comments with the eval function. I resolve my needed with this kind of code:
var json = JSON.parse(myjsonasastring);
var descriptiontobeadded = [
{ dt: "Text content", dd: "content" },
{ dt: "Author name", dd: "author.name" }
];
$.each(descriptiontobeadded, function(key, val) {
var dt = '<dt>' + val.dt + '</dt>';
description.append(dt);
var dl = '<dd>' + eval('json.' + val.dd) + '</dd>';
description.append(dl);
});

Categories

Resources