JSON data not showing in HTML [duplicate] - javascript

This question already has answers here:
Uncaught Typeerror: cannot read property 'innerHTML' of null
(12 answers)
Closed 5 years ago.
I have some JSON data i would like to render on a page with specific keys(those keys being name, linkURL, image and price). I made a simple div with an id of jsonData and popped the JSON data in a variable however, for some reason, I keep getting
Uncaught TypeError: Cannot read property 'innerHTML' of null'
I'm guessing I have a spelling mistake somewhere that I'm blind too?
Any advice on how I can get this data into the div?
Here is my HTML
<body>
<div id="jsonData"></div>
</body>
Here is my JS
var obj = {
'placements': [
{
'id': '029148',
'name': 'Woodblock Play Suit',
'linkURL':'http://www.warehouse.co.uk/gb/just-arrived/all/woodblock-play-suit/029148.html',
'imageURL':'http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw0f93fcd4/images/hi-res/warehouse_02914899_2.jpg',
'price':'46.00'
},
{
'id':'0294526806',
'name':'Smock Dress',
'linkURL':'http://www.warehouse.co.uk/gb/just-arrived/all/smock-dress/0294526806.html',
'imageURL':'http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dwc9d5ea05/images/hi-res/warehouse_02945268_5.jpg',
'price':'39.00'
},
{
'id':'0297180006',
'name':'Cami',
'linkURL':'http://www.warehouse.co.uk/gb/just-arrived/all/cami/0297180006.html',
'imageURL':'http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw4b954022/images/hi-res/warehouse_02971800_2.jpg',
'price':'9.00'
},
{
'id':'0298473606',
'name':'Asymmetric Wrap Cami Dress',
'linkURL':'http://www.warehouse.co.uk/gb/just-arrived/all/asymmetric-wrap-cami-dress/0298473606.html',
'imageURL':'http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw686fea84/images/hi-res/warehouse_02984736_2.jpg',
'price':'46.00'
},
{
'id':'0297155306',
'name':'Casual Stripe Tee',
'linkURL':'http://www.warehouse.co.uk/gb/just-arrived/all/casual-stripe-tee/0297155306.html',
'imageURL':'http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw4609af3e/images/hi-res/warehouse_02971553_2.jpg',
'price':'16.00'
}
]
};
var divId = document.getElementById('jsonData');
for(var i=0;i<obj.placements.length;i++)
for(var keys in obj.placements[i]){
console.log(keys +obj.placements[i][keys]);
divId.innerHTML = divId.innerHTML + '<br/>'+ keys + obj.placements[i][keys];
}

Make sure your script tag is placed directly above the closing </body> tag. Your script is likely broken because when the code is being run, <div id="jsonData"></div> is not yet available.
For displaying just the images, here's an example:
var obj = {
'placements': [
{
'id': '029148',
'name': 'Woodblock Play Suit',
'linkURL':'http://www.warehouse.co.uk/gb/just-arrived/all/woodblock-play-suit/029148.html',
'imageURL':'http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw0f93fcd4/images/hi-res/warehouse_02914899_2.jpg',
'price':'46.00'
},
{
'id':'0294526806',
'name':'Smock Dress',
'linkURL':'http://www.warehouse.co.uk/gb/just-arrived/all/smock-dress/0294526806.html',
'imageURL':'http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dwc9d5ea05/images/hi-res/warehouse_02945268_5.jpg',
'price':'39.00'
},
{
'id':'0297180006',
'name':'Cami',
'linkURL':'http://www.warehouse.co.uk/gb/just-arrived/all/cami/0297180006.html',
'imageURL':'http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw4b954022/images/hi-res/warehouse_02971800_2.jpg',
'price':'9.00'
},
{
'id':'0298473606',
'name':'Asymmetric Wrap Cami Dress',
'linkURL':'http://www.warehouse.co.uk/gb/just-arrived/all/asymmetric-wrap-cami-dress/0298473606.html',
'imageURL':'http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw686fea84/images/hi-res/warehouse_02984736_2.jpg',
'price':'46.00'
},
{
'id':'0297155306',
'name':'Casual Stripe Tee',
'linkURL':'http://www.warehouse.co.uk/gb/just-arrived/all/casual-stripe-tee/0297155306.html',
'imageURL':'http://demandware.edgesuite.net/aaxe_prd/on/demandware.static/-/Sites-WAREHOUSE/default/dw4609af3e/images/hi-res/warehouse_02971553_2.jpg',
'price':'16.00'
}
]
};
var divId = document.getElementById('jsonData');
for(var i=0;i<obj.placements.length;i++) {
divId.innerHTML += '<img src="' + obj.placements[i]['imageURL'] + '" style="max-width: 100px; float: left; padding: 5px;" />';
}
<body>
<div id="jsonData"></div>
</body>

Modify your code:
document.addEventListener('DOMContentLoaded', function(e) {
var divId = document.getElementById('jsonData');
for(var i=0;i<obj.placements.length;i++)
for(var keys in obj.placements[i]){
console.log(keys +obj.placements[i][keys]);
divId.innerHTML = divId.innerHTML + '<br/>'+ keys + obj.placements[i][keys];
}
});
Update:
In case you need some certain keys. I would update your code this way:
document.addEventListener('DOMContentLoaded', function(e) {
var result = "";
var allowed = ['some', 'key', 'allowed'];
// some ES5 magic
obj.placements.forEach(el => {
var keys = Object.keys(el).filter(key => allowed.indexOf(key) !== -1);
result+= '<br/>'+ keys + obj.placements[i][keys];
});
document.getElementById('jsonData').innerHTML = result;
});

fist of all you need to add jquery library.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
use following each loop
var html_data = '';
$.each(obj.placements,function(k,v){
$.each(v,function(key,value){
html_data += key+' : '+value+"<br/>";
});
});
$("#jsonData").html(html_data);
Thanks.

Related

How to display inner child Boolean values a checkbox based on JSON structure?

I am implementing table based on JSON Data. I am able to get two levels, But I am not able to get most inner child values.
http://jsfiddle.net/varunPes/0n9fmawb/43/
var data = {
"managment":
{
"Notice":{
"Red color" :{"View":true,"edit":true,"delete":true} ,
"Yellow color":{"View":true,"edit":true,"delete":true} ,
"Specail color":" checkoxes"
},
"Black Notice":{"black":" Checkboxes"}
},
"Faculty":
{
"salary":{"list":" checkboxes"},
},
};
var zoneHtml = '';
for(var zoneKey in data) {
zoneHtml+='<div class="zone">';
zoneHtml+= ('<h1>'+zoneKey+'</h1>');
var jsonData = data[zoneKey];
for(var listUI in jsonData) {
zoneHtml+='<div class="jsonData">';
zoneHtml+=('<h2 class="prop">'+listUI+'</h2>');
var ports = jsonData[listUI];
zoneHtml+='<ul class="port">';
for(var port in ports) {
zoneHtml+=('<li>'+port+':'+ports[port] +'</li>');
}
zoneHtml+='</ul>';
zoneHtml+='</div>';
}
zoneHtml+=('</div>');
}
$("#zone").html(zoneHtml);
.jsonData{
margin-left:10%;
}
.port{
margin-left:10%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="zone"></div>
Expacted Output:
I am attaching exacted output as a screen shot:
When I am trying to put inner object "red color" three fields "delete", "enable", "view", Then it is showing object like below:
Red color:[object Object]
First I want to get inner object value after that I will put checkbox. Thanks in advance. Your answer is valuable guys:
You should check if property is an object, then you need to loop through each property again. You can play with your logic and make as a recursion function.
I have updated your logic:
var data = {
"managment":
{
"Notice":{
"Red color" :{"delete":true,"enable":true,"view":true} ,
"Yellow color":{"delete":true,"enable":true,"view":true},
"Specail color":" checkoxes"
},
"Black Notice":{"black":" Checkboxes"}
},
"Faculty":
{
"salary":{"list":" checkboxes"},
},
};
var zoneHtml = '';
for(var zoneKey in data) {
zoneHtml+='<div class="zone">';
zoneHtml+= ('<h1>'+zoneKey+'</h1>');
var jsonData = data[zoneKey];
for(var listUI in jsonData) {
zoneHtml+='<div class="jsonData">';
zoneHtml+=('<h2>'+listUI+'</h2>');
var ports = jsonData[listUI];
zoneHtml+='<ul class="port">';
for(var port in ports) {
if (typeof ports[port] === 'object') {
zoneHtml+='<li>'+port+':';
zoneHtml+='<ul>'
for (var i in ports[port]) {
zoneHtml+='<li>'+i+':' + ports[port][i] + '</li>';
}
zoneHtml += '</ul></li>';
} else {
zoneHtml+=('<li>'+port+':'+ports[port] +'</li>');
}
}
zoneHtml+='</ul>';
zoneHtml+='</div>';
}
zoneHtml+=('</div>');
}
$("#zone").html(zoneHtml);
$("#zone").html(zoneHtml);
.jsonData{
margin-left:10%;
}
.port{
margin-left:10%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="zone"></div>
Please update the code as you needed.

Get all cards from Trello and store details

I'm trying to write some simple Javascript that uses the Trello API to get all boards / lists / cards from my account and add them into an sortable table (using the Datatables jquery plugin).
I've so far managed to write a jsfiddle that gets all this information and writes it to a page, but I can't work out how to store all this information into some sort of data structure that can then be passed to the datatable plugin.
This is the fiddle I have so far that gets the data from Trello:
JS Fiddle Link
var carddata = [];
Trello.members.get("me", function(member) {
$("#fullName").text(member.fullName);
var boardUrl = "";
boardUrl = "members/me/boards";
Trello.get(boardUrl, function(boards) {
$.each(boards, function(ix, board) {
Trello.get("/boards/" + board.id + "/lists", function(lists) {
$.each(lists, function(ix, list) {
Trello.get("lists/" + list.id + "/cards", function(cards) {
$.each(cards, function(ix, card) {
console.log("boardname: " + board.name + "; list name: " + list.name + "; card name: " + card.name);
carddata.push(
"boardname: " + board.name +
"; list name: " + list.name +
"; card name: " + card.name
);
var $tablerow = "";
$tablerow = $(
"<tr><td>" + board.name +
"</td><td>" + list.name +
"</td><td>" + card.name +
"</td></tr>"
).appendTo("#table_body");
});
/*
for (i = 0; i < carddata.length; i++) {
console.log("carddata: " + carddata[i]);
}
*/
});
});
});
});
});
});
// **** carddata array is empty at this point ****
for (i = 0; i < carddata.length; i++) {
console.log("carddata: " + carddata[i]);
}
It loops through all boards, lists and cards and currently adds what it finds to a html table (and also an array). I then use the Datatables plugin to change that HTML table into a sortable table.
However the plugin is seeing the HTML table as empty (from what I can see), I presume this is because of something like the plugin code being called before the Javascript builds up the table in HTML.
So instead I planned to add all the data into an array, and then pass that array into the datatable as a datasource, but I can 't see how to make the array accessible outside the very inner loop. From doing some searches I think this is to do with closures and scope but I'm struggling to understand how they work (I'm very new to Javascript).
Is anyone able to help me get this basic code working and show me what I'm doing wrong?
Thanks,
David.
The following code snippet demonstrate how to add data to data table after table created. For how to wait for all asyn requests completed, setTimeout is used to simulate Trello.get method for the asyn behavior.
var boardHash = {};
var listHash = {};
var updateLoggedIn = function() {
$("#loggedout").toggle(!isLoggedIn);
$("#loggedin").toggle(isLoggedIn);
};
var loadCardData = function(){
var carddata = [];
var loadMember = function() {
setTimeout(function(){
console.log("Member loaded");
loadBoard();
},2000);
}
var loadBoard = function() {
setTimeout(function(){
console.log("Boards loaded");
var listPromises = [];
loadList(["boardA","boardB","boardC"],listPromises);
$.when.apply($, listPromises).then(function(){
table.rows.add(carddata).draw("");
});
},1000);
};
var loadList = function(boards,listPromises){
$.each(boards,function(boardIndex, boardValue){
var listDefered = $.Deferred();
listPromises.push(listDefered.promise());
setTimeout(function(){
console.log(boardValue+" lists loaded");
var cardPromises = [];
loadCard(["listA","listA","listC"],boardValue,cardPromises);
$.when.apply($, cardPromises).then(function(){
listDefered.resolve();
});
},(boardIndex+1)*900);
});
};
var loadCard = function(lists,boardValue,cardPromises){
$.each(["listA","listA","listC"],function(listIndex, listValue){
var cardDefered = $.Deferred();
cardPromises.push(cardDefered.promise());
setTimeout(function(){
console.log(boardValue+" "+listValue+" cards loaded");
$.each(["cardA","cardB","cardC"],function(cardIndex, cardValue){
carddata.push({
"boardName":boardValue,
"listName":listValue,
"cardName":cardValue
});
});
cardDefered.resolve();
},(listIndex+1)*800);
});
};
loadMember();
};
var logout = function() {
updateLoggedIn();
};
$("#connectLink")
.click(function() {
loadCardData();
});
$("#disconnect").click(logout);
var consoleLine = "<p class=\"console-line\"></p>";
console = {
log: function(text) {
$("#console-log").append($(consoleLine).html(text));
}
};
var table = null;
$(document).ready( function () {
table = $('#table_id').DataTable({
columns: [
{ data: 'boardName' },
{ data: 'listName' },
{ data: 'cardName' }
]
});
} );
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<div id="loggedout">
<a id="connectLink" href="#">Connect To Trello</a>
</div>
</head>
<div id="loggedin">
<div id="header">
Logged in to as <span id="fullName"></span>
<a id="disconnect" href="#">Log Out</a>
</div>
<div id="output"></div>
</div>
<table id="table_id" class="display" border=1>
<thead>
<tr>
<th>Board</th>
<th>List</th>
<th>Card</th>
</tr>
</thead>
<tbody id="table_body">
</tbody>
</table>
<div id="console-log"></div>
</html>
For adding data to data table
So in your code, add the columns options to the data table, and use rows.add method to add data to data table when all ajax request are done.
Wait for all ajax request completed
The most tricky part is how to ensure all response are done, this can be achieved by $.Deferred() and $.when.apply, see JQuery document and What does $.when.apply($, someArray) do? for more details.

How to generate dynamic HTML with jQuery in a loop and a JSON with parameters?

I would like to generate a HTML file out of an JSON in a loop. For example that's the result I want:
<div class="card">
<p>My name is: Peter</p>
<!-- another code -->
<p>My job is: Programmer</p>
<!-- some more code -->
</div>
<div class="card">
<p>My name is: John</p>
<!-- another code -->
<p>My job is: Programmer</p>
<!-- some more code -->
</div>
<!-- and so on ... -->
But I want to generate all that HTML (that means: all the "card"-divs) dynamically just out of an simple JSON like:
[
{ "Name": "Peter", "Job": "Programmer" },
{ "Name": "John", "Job": "Programmer" },
{ "Name": "Kevin", "Job": "Scientist" },
]
Unfortunately I'm just learning some JS/jQuery and don't know exactly, how to do that with jQuery in a loop. Anyone some help?
Try this one:
function createCard(cardData) {
var cardTemplate = [
'<div class="card">',
'<p>My name is: ',
cardData.Name || 'No name provided',
'</p>',
'<p>My job is: ',
cardData.Job || 'No job provided',
'</p></div>'
];
// a jQuery node
return $(cardTemplate.join(''));
}
var data = [
{ "Name": "Peter", "Job": "Programmer" },
{ "Name": "John", "Job": "Programmer" },
{ "Name": "Kevin", "Job": "Scientist" },
];
var cards = $();
// Store all the card nodes
data.forEach(function(item, i) {
cards = cards.add(createCard(item));
});
// Add them to the page... for instance the <body>
$(function() {
$('body').append(cards);
});
Take a look.
https://jsfiddle.net/c0w6jbpa/
$.each(arr, function(i){ //Loop the array
var templateString = '<div class="card"><p>My name is: '+arr[i].Name+'</p><p>My job is: '+arr[i].Job+'</p></div>';
//You can get the prop of array with arr[i].Name
$('#test').append(templateString);
})
You can use $.each for loop an array.
Link: http://api.jquery.com/jquery.each/
Take a look
var jsonData = '[{"Name":"Peter","Job":"Programmer"},{"Name":"John","Job":"Programmer"},{"Name":"Kevin","Job":"Scientist"}]';
UpdateView("#testDiv",jsonData);
function UpdateView(divId,jsonData){
var htmlTemplate = '<div class="card"><p>My name is: {0}</p><!-- another code --><p>My job is: {1}</p><!-- some more code --></div>';
var dataList= JSON.parse(jsonData);
var html ="";
dataList.forEach(function(item){
var temp = htmlTemplate.replace("{0}",item.Name);
temp =temp.replace('{1}',item.Job);
html += temp;
});
$(divId).html(html);}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='testDiv'>
</div>
This will help you to generate divs :
var data = [
{"Name":"Peter","Job":"Programmer"},
{"Name":"John","Job":"Programmer"},
{"Name":"Kevin","Job":"Scientist"},
];
var divs = "";
for( var i = 0; i < data.length;++i) {
divs += "<div class='card'>"
+"<p>My name is: "+data[i].Name+"</p>"
+"<p>My job is: "+data[i].Job+"</p>"
+"</div>";
}
$("p").append(divs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<P> Hi</P>
In pure JavaScript, you could use a string template and append the HTML to a container, similar to this.
var jsonData = '[{"Name":"Peter","Job":"Programmer"},{"Name":"John","Job":"Programmer"},{"Name":"Kevin","Job":"Scientist"}]'
var htmlTemplate = '<div class="card"><p>My name is: {0}</p><!-- another code --><p>My job is: {1}</p><!-- some more code --></div>'
var newHtml = ''
var container;
var tempContainer;
data = JSON.parse(jsonData);
var addPeople = function() {
for (var i = 0; i < data.length; i++) {
newHtml = htmlTemplate.replace('{0}', data[i].Name).replace('{1}', data[i].Job)
tempContainer = document.createElement('div');
tempContainer.innerHTML = newHtml;
container = document.getElementById('people');
container.appendChild(tempContainer);
}
};
document.addEventListener('DOMContentLoaded', addPeople, false);
<div id="people"></div>
Depending on the browser you might need use document.attachEvent("onreadystatechange"...) instead ofdocument.addEventListener` but in jQuery this has been normalized.
In jQuery you can do the following:
var jsonData = '[{"Name":"Peter","Job":"Programmer"},{"Name":"John","Job":"Programmer"},{"Name":"Kevin","Job":"Scientist"}]'
var htmlTemplate = '<div class="card"><p>My name is: {0}</p><!-- another code --><p>My job is: {1}</p><!-- some more code --></div>'
var newHtml = ''
var container;
var tempContainer;
data = JSON.parse(jsonData);
var addPeople = function(){
for (var i = 0; i < data.length; i++) {
newHtml = htmlTemplate.replace('{0}', data[i].Name).replace('{1}', data[i].Job)
container = $('#people');
container.append(newHtml);
}
};
$('document').ready(function() {
addPeople();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="people"></div>
No need for jquery.
cards.forEach(function(card){
document.body.innerHTML += "<div class='card'><p>My Name is "+card.Name+"</p><p>My Job Is "+card.Job+"</p></div>"
});
You better learn how to do it in native javaScript:
JSON.parse(MyJsonArray).forEach(function (person){
document.getElementById("cardParentEl").innerHTML += ' my name is:'+ person.Name +' my job is:'+ person.Job+'';
});
As you can see, it's messy.. a better way to dynamically create html, if you have to do it very often in your code is to use template engines
Sorry for indentation, I wrote this on a phone

Zingchart - passing a function to the tooltip

Is it possible to pass a function to the tooltip key in the Zingchart Json?
I tried the following so far:
$scope.applyTooltip = function (timestamp) {
console.log(timestamp);
var tooltip = "<div>";
var data = {
timestamp1: {
param1: "bla",
param2: "foo,
},
...
}
for(var param in data){
console.log(param);
tooltip += param+": "+data[param]+"<br>";
}
tooltop += "</div>;
return tooltip;
}
$scope.graphoptions = {
//...
//just displaying the relevant options
plot: {
"html-mode": true,
tooltip: $scope.applyTooltip("%kt"),
}
}
}
But the function gets the string "%kt" as it is and not the wanted X-Value of the hovered Plot. So how is it possible to pass the X-Value in the Function?
ZingChart does not allow passing in functions through the configuration object.
Instead, there is a property called "jsRule" which allows you to pass the name a function to be evaluated during each tooltip event.
tooltip : {
jsRule : "CustomFn.formatTooltip()"
}
Inside that function, a parameter will be available that will contain information about the node you moused over such as value, scaletext, plotindex, nodeindex, graphid, and more. Simply return an object for the tooltip (including the formatted text) and ZingChart will take care of the rest. Example provided down below.
The one caveat to jsRule is that the function name has to be accessible globally since ZingChart does not accept inline functions. We are aware of this issue and are planning for this to be an option in future versions.
CustomFn = {};
var myConfig = {
type: "line",
tooltip : {
jsRule : "CustomFn.formatTooltip()"
},
series : [
{
values : [1,3,2,3,4,5,4,3,2,1,2,3,4,5,4]
},
{
values : [6,7,8,7,6,7,8,9,8,7,8,7,8,9,8]
}
]
};
CustomFn.formatTooltip = function(p){
var dataset = zingchart.exec('myChart', 'getdata');
var series = dataset.graphset[p.graphindex].series;
var tooltipText = "";
for (var i=0; i < series.length; i++) {
tooltipText += "Series " + i + " : " + series[i].values[p.nodeindex] + "";
if (i !== series.length-1) {
tooltipText += "\n";
}
}
return {
text : tooltipText,
backgroundColor : "#222"
}
}
zingchart.render({
id : 'myChart',
data : myConfig,
height: 400,
width: 600
});
<!DOCTYPE html>
<html>
<head>
<script src= 'https://cdn.zingchart.com/2.3.1/zingchart.min.js'></script>
</head>
<body>
<div id='myChart'></div>
</body>
</html>

creating a Json object with arrays structure

I want to create a Json object which has an array through javascript when a function is been called. (for example "list()"). And the function should return a json object for the following.
{
"config": [
{
"name":"steve",
"id":"123"
},
{
"name":"adam",
"id":"124"
},
{
"name":"eve",
"id":"125"
}
]
}
Thank you ...
i know that "google the question" answers are not appreciated here but seriously
how hard is it to type "javascript json" into google? and follow the very first link? here: http://www.json.org/js.html ?
Is this what you looking for
var yourArray = [
{
"name":"steve",
"id":"123"
},
{
"name":"adam",
"id":"124"
},
{
"name":"eve",
"id":"125"
}
];
JSON lib
var myJsonString = JSON.stringify(yourArray);
JQuery json
var encoded = $.toJSON( yourArray );
Json is simply the string representation for the object. The whole point of Json is that the syntax itself is valid javascript which can be parsed as an object.
It's hard to understand what you're asking here. If you just want to know how to work with the object from code you can just do something like this:
var myObj = {};
myObj.config = [];
myObj.config[0] = {};
myObj.config[0].name = "steve";
myObj.config[0].id = "123";
myObj.config[1] = {};
myObj.config[1].name = "adam";
myObj.config[1].id = "124";
myObj.config[2] = {};
myObj.config[2].name = "eve";
myObj.config[2].id = "125";
This is exactly equivalent to this:
var myObj = {
"config": [
{
"name":"steve",
"id":"123"
},
{
"name":"adam",
"id":"124"
},
{
"name":"eve",
"id":"125"
}
]
};
I have done complete bin to parse json object from array json string and shows on html format using jQuery.
HTML:
<div class="jsonobj">
</div>
<br/>
<input type="button" value="Run" id="btnrun"/>
<input type="button" value="Reset" id="btnreset"/>
CSS:
.jsonobj{
background:#ddd;
}
.jsonobj .key{
display:inline-block;
clear:both;
color:#993322;
}
.jsonobj .val{
color:#336622;
display:inline-block;
margin-left:7px;
}
input[type=button]{
border:1px solid #333;
}
input[type=button]:hover{
background:#eee;
}
JQuery:
function list(a) {
if (a == null || typeof(a) == "undefined") return false;
return JSON.parse(a);
}
$(function() {
$("#btnrun").click(function() {
var jsonarr = '{"config": [{ "name":"steve", "id":"123"}, { "name":"adam", "id":"124"},{"name":"eve","id":"125"}]}';
//Convert into JSON Object
var jsonObject = list(jsonarr);
var i = 0,
html = '';
$.each(jsonObject.config, function(k, val) {
html += "<div class='key'>Name:</div><div class='val'>" + val.name + "</div>";
html += "<br/><div class='key'>Id:</div><div class='val'>" + val.id + "</div><br/>";
});
if (html != '') {
$(".jsonobj").css({
'padding': '5px',
'border': '1px solid #222'
});
$(".jsonobj").html(html);
}
});
$("#btnreset").click(function() {
$(".jsonobj").css({
'padding': '0px',
'border': '0px'
});
$(".jsonobj").html("");
});
//Trigger Run on ready
$("#btnrun").trigger('click');
});
TRY it on http://codebins.com/bin/4ldqpai

Categories

Resources