getJSON displays [object Object] rather than actual values - javascript

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

Related

How do you delete an empty array from javascript?

For reference I have zero javascript knowledge or any coding knowledge. I typically just hook up applications via IPASS applications that don't require any coding knowledge. However, I found out I need to inject some javascript into the application in order to avoid an error message.
I have the below JSON record.
I need to get rid of the empty array (sorry... if it is not an array but an object? Like I said, no javascript knowledge).
In the below code essentially what I want is to completely delete this line, because there is nothing inside the brackets and it is causing errors:
"lineitemsdata": []
Full JSON record below for reference
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [
{
"id": "5230410841",
"type": "company_to_deal"
}
]
}
},
"dealdata": [
{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [
{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}
],
"DealOwner": [
{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}
],
"NetSuiteCustomerID": 1745
}
Item inside object is called a property. If you (for some reason) have to include the property, but don't want it to have any value you can either set it's value to null or undefined.
I suspect I'm going to get criticized for this, but here is a quick and dirty way of removing this specific problem through string replacement. The 'right' way would be to break down your json into separte objects until you get to the level where the offending object lives, remove it, then rebuild it all back. For what it's worth, here's an alternative to that
let json = {
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [{
"id": "5230410841",
"type": "company_to_deal"
}]
}
},
"dealdata": [{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}],
"DealOwner": [{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}],
"NetSuiteCustomerID": 1745
}
json = JSON.stringify(json)
let strstart = json.indexOf('"lineitemsdata":[]');
let commapos = json.lastIndexOf(',', strstart);
json = json.substr(0, commapos) + " " + json.substr(commapos + 1);
json = json.replace('"lineitemsdata":[]', '');
json = JSON.parse(json)
console.log(json)
You can use this to strip any empty lineitems arrays from your json.
Assuming the reference to your record is json
for(dealIdx in json.dealdata) {
for (resultIdx in json.dealdata[dealIdx].associations["line items"].results) {
let lineItemsData = json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
if (lineItemsData != undefined && lineItemsData.length === 0 ) {
delete json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
}
}
}

Using lodash, how I can get the maximum length of nested array object

I need to take the data from below mentioned array of object which has maximum length of nested array object. As per below my request, id : 2 values has 3 objects, result will be as mentioned below.
Anyone help me using lodash or some javascript function to achieve this.
Sample Request:
[{
"id": 1,
"values": [
{
"sub": "fr",
"name": "foobar1"
},
{
"sub": "en",
"name": "foobar2"
}
]
},
{
"id": 2,
"values": [
{
"sub": "fr",
"name": "foobar3"
},
{
"sub": "en",
"name": "foobar4"
},
{
"sub": "ts",
"name": "foobar5"
},
]
}]
Expected output:
"values": [
{
"sub": "fr",
"name": "foobar3"
},
{
"sub": "en",
"name": "foobar4"
},
{
"sub": "ts",
"name": "foobar5"
},
]
}]
This can be achieved using the native javascript reduce function as follows
var source = [...];
source.reduce((max, cur) => cur.values.length > max.values.length ? cur : max, source[0])

Facing Issue on Getting First Level Of Data in JSON File

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

push the object to array, according to order number in javascript

Below array i have 5 objects, with random order value, need to arrange the array as per the order key in object
i want push each object another array as per order.
var array = [
{
"name": {
"text": "javascript"
},
"order": {
"text": "4"
}
},
{
"name": {
"text": "angualr js"
},
"order": {
"text": "2"
}
},
{
"name": {
"text": "Ios"
},
"order": {
"text": "3"
}
},
{
"name": {
"text": "PHP"
},
"order": {
"text": "5"
}
}, {
"name": {
"text": "C"
},
"order": {
"text": "5"
}
}
]
can any explain how to follow the logic.
Just sort the array with Array.prototype.sort, it accepts a function as parameter to compare two items.
array.sort(function(a, b) {
return parseInt(a.order.text, 10) - parseInt(b.order.text, 10);
});

read JSON object with jQuery

I have this JSON object:
"Master": {
"nodeType": "Test",
"label": "Master",
"nodes": {
"event": {
"nodeType": "Test",
"label": "Test",
"itemTemplate": {
"label": "Test",
"properties": {
"icon": {
"label": "Test",
"description": "Test",
"valueType": "STRING",
"value": ""
}
}
},
"items": [
{
"icon": "test 2",
},
{
"icon": "test 1",
}
]
}
}
I want to access the items section. I've tried the following:
var obj = jQuery.parseJSON(json_object); //json object
alert(obj.nodes.items[0].icon); //Uncaught TypeError: Cannot read property 'items' of undefined
var items;
items = obj.Master.nodes.event.items;
alert(items[0].icon);
items result in an array
note your json is incorrect as is missing a leading { and two trailing }
json_object = '{ "Master": {
//
//
//
} }';
If not correct jQuery.parseJSON will fail.
Your JSON defines a single key called "Master". Try:
alert(obj.Master.nodes.items[0].icon);
console.log(obj.Master.nodes.event.items[0].icon)
check structure of your json here : http://jsonviewer.stack.hu/
that will help you to understand node inheritance
alert(obj.Master.nodes.event.items[0].icon);
and validate your json
http://jsonlint.com/

Categories