Facing Issue on Getting First Level Of Data in JSON File - javascript

I have an external JSON file called movie.json and is like following format
{
"action":
[
{ "id": "1001", "name": "Matrix" },
{ "id": "1002", "name": "IP Man" },
{ "id": "1003", "name": "Revenge" }
],
"comedy":
[
{ "id": "2001", "type": "Iceman" },
{ "id": "2002", "type": "Pat & Mat" },
{ "id": "2003", "type": "Sugar" }
],
"animation":
[
{ "id": "3001", "type": "Frozen" },
{ "id": "3002", "type": "Tangled" },
{ "id": "3003", "type": "Croods" }
]
}
in my HTML I have a bootstrap Tab component like
<ul class="nav nav-tabs" role="tablist">
</ul>
can you please let me know how I can get access to upper level of JSON file (action, comedy, animation and populate them as li in .nav-tabs dynamically
I already tried
$.getJSON('data.json', function (data) {
for (i = 0; i < data.length; i++) {
$('.nav-tabs').append('<li role="presentation" >'+data[0]+'</li>')
}
});
but it is not doing the job. Can you please let me know how to fix this? Thanks

You can use $.each() to iterate the data. key will be the "top level" and val the content
$.getJSON('data.json', function (data) {
$.each( data, function( key, val ) {
$('.nav-tabs').append('<li role="presentation" >'+key+'</li>')
});
});

You treating object like an array, its a simple object Use for-in loop
The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
var data = {
"action": [{
"id": "1001",
"name": "Matrix"
},
{
"id": "1002",
"name": "IP Man"
},
{
"id": "1003",
"name": "Revenge"
}
],
"comedy": [{
"id": "2001",
"name": "Iceman"
},
{
"id": "2002",
"name": "Pat & Mat"
},
{
"id": "2003",
"name": "Sugar"
}
],
"animation": [{
"id": "3001",
"name": "Frozen"
},
{
"id": "3002",
"name": "Tangled"
},
{
"id": "3003",
"name": "Croods"
}
]
};
for (var i in data) {
$('.nav-tabs').append('<li><strong>' + i + '<strong></li>')
for (var j = 0; j < data[i].length; j++) {
var obj = data[i][j];
$('.nav-tabs').append('<li>' + obj.name + '</li>')
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="nav nav-tabs" role="tablist">
</ul>

// jsonObj is your json object
jQuery.each(jsonObj, function(key,val) {
//key will have action,comedy and animation
console.log(key,val)
});

Related

Remove Null value when delete a json portion using javascript

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)

How to get the corresponding value from two objects

I have first data object which has a list of cafe, and second data object which has a list of cafe types.
I need find, get and display the corresponding type value from first data object and ID value from second data object.
For example: in list of cafe, I have Pinta with "type" : "3", it means that 3 is Bar from second object.
First object:
{
"list": {
"item": [
{
"ID": "31",
"name": "Staut",
"type": "1",
},
{
"ID": "34",
"name": "Pinta",
"type": "3",
}
]
}
}
And second object:
{
"list": {
"item": [
{
"ID": "1",
"name": "Restaurant",
},
{
"ID": "2",
"name": "Cafe",
},
{
"ID": "3",
"name": "Bar",
}
]
}
}
I can do it with Lodash. It is right, but I can't display it and it uses high memory.
getValues: function() {
_.forEach(CafeJSON.list.item, function(cafeValue) {
_.forEach(TypeJSON.list.item, function(typeValue){
if (cafeValue.type == typeValue.ID) {
console.log("Cafe name is: ", cafeValue.name, "and type is: ", typeValue.name)
}
})
})
}
Result:
I'd simplify the types object down to a object having key value pairs in the form of '3': 'Bar', then loop the items once, overriding the type property's value.
let list = {
"list": {
"item": [{
"ID": "31",
"name": "Staut",
"type": "1",
},
{
"ID": "34",
"name": "Pinta",
"type": "3",
}
]
}
}
let types = {
"list": {
"item": [{
"ID": "1",
"name": "Restaurant",
},
{
"ID": "2",
"name": "Cafe",
},
{
"ID": "3",
"name": "Bar",
}
]
}
}
let typesSimplified = types.list.item.reduce((a, b) => {
a[b.ID] = b.name;
return a;
}, {});
list.list.item.forEach(e => {
e.type = typesSimplified[e.type];
});
console.log(list);

json to nested ul li jquery / javascript

I am creating dynamic json using javascript from a drag and drop builder, Now I am unable to convert the json to Nested Ul li. The json is below.
[
{
"id": "11",
"name": "BALANCE"
},
{
"id": "p1",
"name": "Conditions",
"nodes": [
{
"id": "p1-13",
"name": "SPINAL CORD INJURY",
"nodes": [
{
"id": "p1-13-12",
"name": "STROKE",
"nodes": [
{
"id": "p1-13-12-17",
"name": "REACHING"
}
]
}
]
}
]
},
{
"id": "p1-16",
"name": "STRETCHES"
},
{
"id": "p1-11",
"name": "BALANCE"
}
]
You can create a function and call recursively if there is nodes in item.
var json = [{"id":"11","name":"BALANCE"},{"id":"p1","name":"Conditions","nodes":[{"id":"p1-13","name":"SPINAL CORD INJURY","nodes":[{"id":"p1-13-12","name":"STROKE","nodes":[{"id":"p1-13-12-17","name":"REACHING"}]}]}]},{"id":"p1-16","name":"STRETCHES"},{"id":"p1-11","name":"BALANCE"}];
function createUl(data, $elm) {
data.forEach(function(item) {
var $li = $('<li><span>' + item.name + '</span></li>');
$elm.append($li);
if (item.nodes) {
var $ul = $('<ul></ul>');
$li.append($ul);
createUl(item.nodes, $ul);
}
});
};
createUl(json, $('ul'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>

Trying to pick data from a JSON response text

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.

getJSON displays [object Object] rather than actual values

I have a JSON and I need to get this JSON and put in the html as a ul li list. It gets the value as object and displays [object Object] in html. If I modify the json then it works. so there is probably something wrong in my script where I am not able to loop throught he json file properly. Can some one help please:
MY JSON IS:
[
{
"us":"USA"
},
{
"fr":"FRANCE"
},
{
"es":"Spain"
},
{
"sa":"South Africa"
}
]
AND JS IS
<script>
$.getJSON('jsonfile', function(data) {
var items = [];
$.each(data ,function(key,val) {
items.push('<li id="'+ key +'">' + val +'</li>');
});
$('<ul />' , {
'class':'new-div',
html:items.join('')
}).appendTo('body');
});
</script>
UPDATED JSON:
[
{
"items":
{
"item":
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
]
}
}
]
The data you're looping over is the array, which has objects. So your key will be 0, 1, etc., and the val will be the object at that position in the array.
Your JSON structure actually makes it a bit of a pain to output, because each of your objects only has one property, but the property name varies from object to object. You can do it, by looping over the object properties even though there's only one of them:
var items = [];
$.each(data ,function(outerKey, outerVal) { // <== Loops through the array
$.each(outerVal, function(key, val) { // <== "Loops" through each object's properties
items.push('<li id="'+ key +'">' + val +'</li>');
});
});
...but I'd change the JSON structure instead. For instance, assuming the keys are unique, your original code would work with this structure:
{
"us":"USA",
"fr":"FRANCE",
"es":"Spain",
"sa":"South Africa"
}

Categories