From the below JSON, how can I retrieve title from the note and notes using a for loop and ajax to retrieve?
{
"infos": {
"info": [
{
"startYear": "1900",
"endYear": "1930",
"timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..",
"timeZoneID": "1",
"note": {
"notes": [
{
"id": "1",
"title": "Mmm"
},
{
"id": "2",
"title": "Wmm"
},
{
"id": "3",
"title": "Smm"
}
]
},
"links": [
{ "id": "1", "title": "Red House", "url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html" },
{ "id": "2", "title": "Joo Chiat", "url": "http://www.the-inncrowd.com/joochiat.htm" },
{ "id": "3", "title": "Bake", "url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery" }
]
}
I tried out the code below but it doesn't work - it either says:
is null
not an object
length is null
r not an object
var detail = eval(xmlhttprequest.responseText)
var rss = detail.infos.info
for(var i = 0; i<rss.length; i++)
startyear += rss[i].startyear
Use
for (i = 0; i < 3; i++) {
alert(JSON.infos.info[0].note.notes[i].title);
}
TRY IT HERE: JSFIDDLE WORKING EXAMPLE
BTW your JSON is not valid. Use this JSON:
var JSON = {
"infos": {
"info": [
{
"startYear": "1900",
"endYear": "1930",
"timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..",
"timeZoneID": "1",
"note": {
"notes": [
{
"id": "1",
"title": "Mmm"
},
{
"id": "2",
"title": "Wmm"
},
{
"id": "3",
"title": "Smm"
}
]
},
"links": [
{
"id": "1",
"title": "Red House",
"url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html"
},
{
"id": "2",
"title": "Joo Chiat",
"url": "http://www.the-inncrowd.com/joochiat.htm"
},
{
"id": "3",
"title": "Bake",
"url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery"
}
]
}
]
}
}
EDIT:
Here is what you want:
var infoLength= JSON.infos.info.length;
for (infoIndex = 0; infoIndex < infoLength; infoIndex++) {
var notesLength= JSON.infos.info[infoIndex].note.notes.length;
for (noteIndex = 0; noteIndex < notesLength; noteIndex++) {
alert(JSON.infos.info[infoIndex].note.notes[noteIndex].title);
}
}
Putting your json into an var called obj, use the following:
obj.infos.info[0].note.notes[0].title
http://jsfiddle.net/Znq34/
Well the "path" to the JSON notes array-like object is:
json.infos.info[0].note.notes;
So you could do something like:
var notes = json.infos.info[0].note.notes;
var titles = [];
for (var i = 0, len = notes.length; i < len; i++)
{
titles.push(notes[i].title);
}
alert('titles is: ' + titles.join(', '));
Fiddle: http://jsfiddle.net/garreh/uDxqD/
Are you using jQuery? ;-)
// Assuming your using "success" in ajax response
success: function(json)
{
var titles = $(json.infos.info[0].note.notes).map(function() {
return this.title;
}).get();
alert(titles.join(', '));
}
First count the length of notes
var len = jsonobject.infos.info.note.notes.length;
Then loops through and get
var title = jsonobject.infos.info.note.notes[i].title;
Related
I am having an json object below. I want to delete a part if the question value is empty. So according to below json I need to delete the id=7602 portion.
[ {
"id": 9333,
"component": "question_pool",
"sub_comp_arr": [
{
"id": 7769,
"component": "question",
"sub_comp_arr": [
{
"id": 2552,
"component": "question_segment",
"value": "Answer1"
},
{
"id": 1011,
"component": "question_segment",
"value": "Answer2"
},
{
"id": 8691,
"component": "question_segment",
"value": "Answer3"
}
],
"type": "single_choice",
"value": "<p>Question1?</p>\n"
},
{
"id": 7602,
"component": "question",
"sub_comp_arr": [
{
"id": 921,
"component": "question_segment",
"value": ""
}
],
"type": "single_choice",
"value": ""
}
]
},{...}
]
I have implemet the code as below
var y= content_json.content_arr;
var keyCount = Object.keys(y).length;
for (var i = 0; i < keyCount; i++) {
var questionCount = (content_json.content_arr[i]['sub_comp_arr']).length;
for (let j = 0; j < questionCount; j++){
var emptyquestion= ((content_json.content_arr[i]['sub_comp_arr'][j]['value']).trim()).length;
if (emptyquestion===0){
delete (content_json.content_arr[i]['sub_comp_arr'][j]);
}
}
}
But the problem is if I use delete (content_json.content_arr[i]['sub_comp_arr'][j]); It is saving a null value on my Json, Which I don't want. How to achieve it
You could use filter instead.
content_json.content_arr[i].sub_comp_arr = content_json.content_arr[i].sub_comp_arr.filter(q => q.value)
var data = [
{
"text": "BEHIND A COMMON MEAL: POLYPHENOLS IN FOOD ",
"id": "445",
"parentid": ""
},
{
"text": "2.2 First Course: Pasta With Tomato Sauce (Polyphenols in Wheat Bran and Tomato Byproducts)",
"id": "441",
"parentid": "445"
},
{
"text": "2.3 A Fresh Side Dish: Mixed Salad (Polyphenols From Fennel, Carrot)",
"id": "442",
"parentid": "445"
},
{
"text": "hello mr.sujai",
"id": "448",
"parentid": "445"
},
{
"text": "polyhierarchy",
"id": "449",
"parentid": "445"
},
{
"text": "INTRODUCTION",
"id": "452",
"parentid": ""
},
{
"text": "1.2 The Tight Biochemical Connection Between Vegetables and Their Byproducts",
"id": "440",
"parentid": "452"
},
{
"text": "OTHER OFF-THE-MENU MISCELLANEOUS",
"id": "454",
"parentid": ""
},
{
"text": "SOMETHING TO DRINK",
"id": "456",
"parentid": ""
},
{
"text": "3.1 Orange Juice (Polyphenols From Orange Byproducts)",
"id": "443",
"parentid": "456"
},
{
"text": "3.2 Wine (Polyphenols From Grape and Wine Byproducts)",
"id": "444",
"parentid": "456"
},
{
"text": "understandings",
"id": "451",
"parentid": "456"
},
{
"text": "Polyphenols",
"id": "453",
"parentid": "451"
},
{
"text": "this is test",
"id": "458",
"parentid": "455"
},
{
"text": "polyhierarchy",
"id": "449",
"parentid": "458"
},
{
"text": "hello",
"id": "447",
"parentid": "449"
},
{
"text": "hi",
"id": "459",
"parentid": "447"
},
{
"text": "polyhierarchy",
"id": "449",
"parentid": "459"
},
{
"text": "testing",
"id": "457",
"parentid": "458"
},
{
"text": "hi test",
"id": "450",
"parentid": "457"
},
{
"text": "speech",
"id": "446",
"parentid": "450"
}]
function jsonTree() {
// Keep a fast lookup dictionary
var dictionary = {};
for (var i = 0; i < data.length; i++) {
dictionary[data[i].id] = data[i];
}
for (var i = 0; i < data.length; i++) {
if (data[i].parentid == 449) {
var test = "";
}
if (data[i].parentid) {
var parent = dictionary[data[i].parentid];
arrData = parent;
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(data[i]);
// arrData.children.push(data[i]);
}
}
}
var arrData = [];
for (var i = 0; i < data.length; i++) {
if (data[i].parentid == 455) {
arrData.push(data[i]);
}
}
document.getElementById("test").innerHTML = JSON.stringify(arrData);
return false;
}
polyhierarchy term having different parent.
for (var i = 0; i < data.length; i++) {
dictionary[data[i].id] = data[i];
}
in this place same id is replaced. polyhierarchy having id is 449. when add to dictionary it is replaced.
Tree structure should be
1. BEHIND A COMMON MEAL: POLYPHENOLS IN FOOD
polyhierarchy
2. this is test
polyhierarchy
hello
hi
polyhierarchy
i need array with parent, child relationship.
There are a few mistakes.
You have duplicate id's for your polyhierarchie element. Because you're building a dictionary to lookup your ids, you're overwriting your child element the second/subsequent time you add it to your object.
{
"text": "polyhierarchy",
"id": "449", //<-- duplicate
"parentid": "459"
}
You have non existant parentIds.
{
"text": "SOMETHING TO DRINK",
"id": "456",
"parentid": "455" // <--- doesn't exist
}
The code got a little more complex than anticipated because of those two issues.
function mapData (data) {
//build a dictionary for: id -> [eles]
var map = data.reduce ((obj, ele) => {
obj[ele.id] = [ //let's make the lookup an array, to support multiple elements with the same id
...obj[ele.id] || [], //keep the existing elements or initialize it to an array
{...ele, children: []}
];
return obj
}, {});
return Object.keys (map).reduce ((arr, key) => {
let eles = map [key] || []; //process all elements
eles.forEach (ele => {
let parents = map [ele.parentid] || [];
let parent = parents [0];
if (!parent) {
parent = map [ele.parentid] = {children: [], root: true}
}
parent.children.push (ele);
if (parent.root && !~arr.indexOf (parent)) arr.push (parent);
});
return arr;
},[])
}
console.log (mapData (data))
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.
Here is my JSON array code
var App = [
{
"id": "123",
"caption": "Test",
"description": "Test Desc"
},
{
"id": "345",
"caption": "adsasdasd",
"description": ""
},
{
"id": "456",
"caption": "adsasdasd",
"description": ""
},
{
"id": "578",
"caption": "adsasdasd",
"description": ""
}
]
i tried with the following code
var obj = $.parseJSON(App);
alert(JSON.stringify(obj,4,null));
var AppLen = obj[i].length;
alert(AppLen);
but i didn't get any solution. Let me know if i missed any thing to get the JSON object array length.
your data is already json format:do like this
var App = [
{
"id": "123",
"caption": "Test",
"description": "Test Desc"
},
{
"id": "345",
"caption": "adsasdasd",
"description": ""
},
{
"id": "456",
"caption": "adsasdasd",
"description": ""
},
{
"id": "578",
"caption": "adsasdasd",
"description": ""
}
];
console.log(App);
console.log(App[0].length);// you can not get length from this because it is not array it's an object now.
var AppLen = App.length;
alert(AppLen);
obj.size() or obj.length
If that dont run try this: Length of a JavaScript object
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the size of an object
var size = Object.size(myArray);
I have an array of objects, which has an array of 'tracks.' What I would like to do is compare the mbid values across all of the track objects, check if there are any duplicates, and store the duplicate track objects into a new array. Any help or guidance?
[
{
"track": [
{
"name": "Radiapathy",
"mbid": "4c0767f1-1c2e-4790-a8d1-ee7f78f0ac84",
"url": "http://www.last.fm/music/The+Velvet+Teen/_/Radiapathy"
},
{
"name": "How Did I Get Here",
"mbid": "64b3078f-89cd-4ad5-bc7a-b43af082b00f",
"url": "http://www.last.fm/music/Odesza/_/How+Did+I+Get+Here"
},
{
"name": "Sunshine Roof",
"mbid": "837db975-c93e-45ca-992c-0c924ef0f34f",
"url": "http://www.last.fm/music/The+Innocence+Mission/_/Sunshine+Roof"
}
]
},
{
"track": [
{
"name": "Traveling",
"mbid": "b40c24b8-3295-4219-af59-855b69958ca2",
"url": "http://www.last.fm/music/Tennis/_/Traveling"
},
{
"name": "Ghost",
"mbid": "6273ae8f-3d2c-44c6-8c0d-53013ba79b4e",
"url": "http://www.last.fm/music/Neutral+Milk+Hotel/_/Ghost"
},
{
"name": "Strange",
"mbid": "5a015df2-6c4a-4192-bea8-14ec5f297713",
"url": "http://www.last.fm/music/Built+to+Spill/_/Strange"
}
]
},
{
"track": [
{
"name": "Radiapathy",
"mbid": "4c0767f1-1c2e-4790-a8d1-ee7f78f0ac84",
"url": "http://www.last.fm/music/The+Velvet+Teen/_/Radiapathy"
},
{
"name": "Let Me Show You Love",
"mbid": "",
"url": "http://www.last.fm/music/Cut+Copy/_/Let+Me+Show+You+Love"
},
{
"name": "Footsteps",
"mbid": "",
"url": "http://www.last.fm/music/Cut+Copy/_/Footsteps"
}
]
}
]
The answer to this question (Elminating duplicates in a JSON object) pretty much answers yours. I've used this (the "Smart(er) way") and modified to suit your array & requirements:
var key = null;
var noDupes = [];
var dupes = [];
for (var i = 0; i < arr.length; i++)
{
// loop through each track:
for (var j = 0; j < arr[i].track.length; j++)
{
key = arr[i].track[j].mbid;
if (!hash.contains(key))
{
hash.add(key);
noDupes.push(arr[i].track[j]); // if not duplicate
}
else
{
dupes.push(arr[i].track[j]); // if duplicate
}
}
}
http://jsfiddle.net/6wspy/