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.
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)
I'm trying to pick specific data from my JSON response which looks like this;
{
"status": "success",
"reservations": [
{
"id": "26630",
"subject": "Subject",
"modifiedDate": "2017-05-16T06:05:12",
"startDate": "2017-05-16T08:00:00",
"endDate": "2017-05-16T09:45:00",
"resources": [
{
"id": "2408",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "3020",
"type": "realization",
"code": "realizationCode",
"name": "realizationName"
},
{
"id": "48",
"type": "room",
"code": "roomCode",
"parent": {
"id": "2",
"type": "building",
"code": "buildingCode",
"name": "buildngName"
},
"name": "RoomName (PC)"
}
],
"description": ""
},
{
"id": "21173",
"subject": "subjectName",
"modifiedDate": "2017-05-16T06:05:20",
"startDate": "2017-05-16T08:00:00",
"endDate": "2017-05-16T16:00:00",
"resources": [
{
"id": "3115",
"type": "realization",
"code": "realizationCode",
"name": "realizationName"
},
{
"id": "2584",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "52",
"type": "room",
"code": "roomCode",
"parent": {
"id": "2",
"type": "building",
"code": "buildingCode",
"name": "buildingName"
},
"name": "roomName (classroom)"
}
],
"description": ""
}
]
}
I've already used JSON.parse() to make it into an object and went through it with for-loops;
var json = JSON.parse(data.responseText);
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 reservations = json.reservations[i];
var resources = json.reservations[i].resources[j];
}
}
}
So I would need to pick out the room names before the "description" key name:
"name": "roomName (PC)"
"name": "roomName (classroom)"
I've kept the JSON response a lot shorter for simplicity's sake but usually there's many more of these room names. The idea is to get all the room names from the JSON response body and push them to an array and just printing them out in order like this;
roomName (PC)
roomName (classroom)
Any quick and effective way to do this?
You can use such way:
const arrays = json.reservations
.filter(reservation => reservation.resources)
.map(reservation =>
reservation.resources.map(resource => resource.name)
)
;
const names = [].concat.apply([], arrays);
Array flatten taken from this question: Merge/flatten an array of arrays in JavaScript?
You can first iterate over the json.reservations array with Array.prototype.forEach() and then iterate again over r.resources and make a Array.prototype.push() if the expression: new RegExp(/roomName/, 'i').test(r.name) is satisfied.
Notice that in your json array have lowercase "name": "roomName (classroom)" and uppercase "name": "RoomName (PC)", so the Regular Expression will not check case sensitive with the flag i and finally the RegExp.prototype.test() will check if roomName is in the r.name.
Code:
var json = {"status": "success","reservations": [{"id": "26630","subject": "Subject","modifiedDate": "2017-05-16T06:05:12","startDate": "2017-05-16T08:00:00","endDate": "2017-05-16T09:45:00","resources": [{"id": "2408","type": "student_group","code": "groupCode","name": "groupName"},{"id": "3020","type": "realization","code": "realizationCode","name": "realizationName"},{"id": "48","type": "room","code": "roomCode","parent": {"id": "2","type": "building","code": "buildingCode","name": "buildngName"},"name": "RoomName (PC)"}],"description": ""},{"id": "21173","subject": "subjectName","modifiedDate": "2017-05-16T06:05:20","startDate": "2017-05-16T08:00:00","endDate": "2017-05-16T16:00:00","resources": [{"id": "3115","type": "realization","code": "realizationCode","name": "realizationName"},{"id": "2584","type": "student_group","code": "groupCode","name": "groupName"},{"id": "52","type": "room","code": "roomCode","parent": {"id": "2","type": "building","code": "buildingCode","name": "buildingName"},"name": "roomName (classroom)"}],"description": ""}]},
result = [],
regex = new RegExp(/roomName/, 'i');
json.reservations.forEach(function (r) {
r.resources.forEach(function (r) {
regex.test(r.name) && result.push({
name: r.name
});
});
})
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can simply do this:
var a = {
"status": "success",
"reservations": [
{
"id": "26630",
"subject": "Subject",
"modifiedDate": "2017-05-16T06:05:12",
"startDate": "2017-05-16T08:00:00",
"endDate": "2017-05-16T09:45:00",
"resources": [
{
"id": "2408",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "3020",
"type": "realization",
"code": "realizationCode",
"name": "realizationName"
},
{
"id": "48",
"type": "room",
"code": "roomCode",
"parent": {
"id": "2",
"type": "building",
"code": "buildingCode",
"name": "buildngName"
},
"name": "RoomName (PC)"
}
],
"description": ""
},
{
"id": "21173",
"subject": "subjectName",
"modifiedDate": "2017-05-16T06:05:20",
"startDate": "2017-05-16T08:00:00",
"endDate": "2017-05-16T16:00:00",
"resources": [
{
"id": "3115",
"type": "realization",
"code": "realizationCode",
"name": "realizationName"
},
{
"id": "2584",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "52",
"type": "room",
"code": "roomCode",
"parent": {
"id": "2",
"type": "building",
"code": "buildingCode",
"name": "buildingName"
},
"name": "roomName (classroom)"
}
],
"description": ""
}
]
}
var b = [];
a.reservations.forEach(function(item){
item.resources.forEach(function(obj){
if(obj.type == "room"){
b.push(obj.name)
}
})
});
console.log(b); //outputs desired array
var jsonStr = "{ \"status\": \"success\", \"reservations\": [ { \"id\": \"26630\", \"subject\": \"Subject\", \"modifiedDate\": \"2017-05-16T06:05:12\", \"startDate\": \"2017-05-16T08:00:00\", \"endDate\": \"2017-05-16T09:45:00\", \"resources\": [ { \"id\": \"2408\", \"type\": \"student_group\", \"code\": \"groupCode\", \"name\": \"groupName\" }, { \"id\": \"3020\", \"type\": \"realization\", \"code\": \"realizationCode\", \"name\": \"realizationName\" }, { \"id\": \"48\", \"type\": \"room\", \"code\": \"roomCode\", \"parent\": { \"id\": \"2\", \"type\": \"building\", \"code\": \"buildingCode\", \"name\": \"buildngName\" }, \"name\": \"RoomName (PC)\" } ], \"description\": \"\" }, { \"id\": \"21173\", \"subject\": \"subjectName\", \"modifiedDate\": \"2017-05-16T06:05:20\", \"startDate\": \"2017-05-16T08:00:00\", \"endDate\": \"2017-05-16T16:00:00\", \"resources\": [ { \"id\": \"3115\", \"type\": \"realization\", \"code\": \"realizationCode\", \"name\": \"realizationName\" }, { \"id\": \"2584\", \"type\": \"student_group\", \"code\": \"groupCode\", \"name\": \"groupName\" }, { \"id\": \"52\", \"type\": \"room\", \"code\": \"roomCode\", \"parent\": { \"id\": \"2\", \"type\": \"building\", \"code\": \"buildingCode\", \"name\": \"buildingName\" }, \"name\": \"roomName (classroom)\" } ], \"description\": \"\" } ] }";
var json = JSON.parse(jsonStr);
var array = [];
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 === "room") {
if (array.indexOf("code")) {
array.push(resource.name);
}
}
}
}
}
console.log(array);
output in console. Please check..
(2) ["RoomName (PC)", "roomName (classroom)"]0: "RoomName (PC)"1: "roomName (classroom)"length: 2__proto__: Array(0)
I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?
You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }
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);
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;