creating a Json object with arrays structure - javascript

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

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.

JSON data not showing in HTML [duplicate]

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.

Convert UL into JSON object

I need to convert an entire UL and it's children elements into a JSON object.
This is what we did:
function getData(el) {
el.find('li').each(function () {
data.push({ "nome": $(this).find('span').html(), "cargo": $(this).find('strong').html() });
});
}
JS Fiddle: https://jsfiddle.net/cbzo0ef2/2/
But all elements are in the same level. In this case, all levels need to be kept.
$(this).parents("ul").length would be trick for you:
function getData(el) {
el.find('li').each(function () {
data.push({ "nome": $(this).find('span').html(), "cargo": $(this).find('strong').html(), "dept": $(this).parents("ul").length })
});
}
You need extra work to render dept to your json structure
see fiddle
This solution will retain the levels in your HTML:
(function($) {
function getData(el) {
var data = [];
el.children('li').each(function () {
var currentElement = $(this);
var nomeElement = currentElement.children('span')[0];
var cargoElement = currentElement.children('strong')[0];
var item = {};
if (nomeElement && cargoElement) {
item.nome = $(nomeElement).html();
item.cargo = $(cargoElement).html();
}
data.push(item);
var child = currentElement.children('ul')[0];
if (child != null) {
item.children = getData($(child));
}
});
return data;
}
var data = getData($('.root'));
console.log(data);
})(jQuery);
See fiddle: https://jsfiddle.net/52t58551/
Using jQuery Children and some recursion you can get every node.
(function($) {
function getData(el) {
var curr = [];
el.children('li, ul').each(function(i, child) {
curr.push({
nodeName: child.nodeName,
nome: $(child).find("> span").text(),
cargo: $(child).find("> strong").text(),
subLevel: getData($(child))
});
});
return curr
}
var result = getData($('.root'));
console.log(JSON.stringify(result));
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="root"> <li><span>a</span><strong>b</strong></li><li><span>c</span><strong>d</strong></li><li><span>e</span><strong>f</strong></li><li> <ul> <li><span>g</span><strong>h</strong></li><li><span>i</span><strong>j</strong></li><li> <ul> <li><span>k</span><strong>l</strong></li></ul> </li></ul> </li></ul>

Alternative to HTML in String

I'm using this code right now, but I'm not really liking the way it looks.
function createPageSettingsPopup(page) {
return '<div class="form-group">' +
'<label for="page-title">Title</label>' +
'<input type="text" class="form-control" id="page-title" value="' + page.title + '">' +
'</div>'
}
Is there any alternative to write the HTML in strings to make it look better?
You could use template engines. This is at the expense of elements in the page, but the code will look much cleaner and the template easier to understand as HTML. Put the template in a script tag with type set to text/template
<script type="text/template" id="tmpl">
<div class="form-group">
<label for="page-title">Title</label>
<input type="text" class="form-control" id="page-title" value="{{pageTitle}}">
</div>
</script>
And modify your function as below. Remember to cache the template.
var template = document.getElementById('tmpl').innerHTML; // cache the HTML
function createPageSettingsPopup(page) {
// Find an replace the {{pageTitle}} with page.title, and then return the HTML string.
return template.replace(new RegExp('{{pageTitle}}', 'gi'), page.title)
}
var template = document.getElementById('tmpl').innerHTML; // cache the HTML
function createPageSettingsPopup(page) {
// Find an replace the {{pageTitle}} with page.title, and then return the HTML string.
return template.replace(new RegExp('{{pageTitle}}', 'gi'), page.title)
}
console.log(
createPageSettingsPopup({title:'Hello World'})
);
<script type="text/template" id="tmpl">
<div class="form-group">
<label for="page-title">Title</label>
<input type="text" class="form-control" id="page-title" value="{{pageTitle}}">
</div>
</script>
The above is a minimal example of a template engine, but there are great ones like mustache, handlebars.js, and pug.js
Assuming ES6 you can use backticks:
return `<div>
...
</div>`;
Or have a look at react, to manipulate your DOM, they use jsx which is really nice:
const element = <h1>Hello, world!</h1>;
In case you are using jQuery, sometimes you can do things like these:
var div = $('div').addClass('form-group');
div.append($('label').attr('for', 'page-title').text('Title');
...
Depending on your problem at hand it might also make sense to have the full html structure written up-front and then just manipulate some content and styling using js. In your example:
$('div#title').show();
$('div#title').find('label.page-title').text('Title');
You can try creating a HTML utility that creates elements, add necessary properties and the returns element.
I have created a small implementation of this utility in sample. Benefit of this is you can modify this utility to work with JSON based structure to create dynamic HTML.
Sample
function createPageSettingsPopup(page) {
var divParams = {
class: 'form-group'
}
var labelParams = {
for: 'page-title'
}
var inputParams = {
type: 'text',
class: "form-control",
id: 'page-title',
value: page.title
}
var div = utils.createMyElement('div', '', divParams);
var label = utils.createMyElement('label', 'Title', labelParams)
var input = utils.createMyElement('input', '', inputParams)
div.appendChild(label);
div.appendChild(input);
document.body.appendChild(div)
}
window.addEventListener('load', function() {
createPageSettingsPopup({
title: "foo"
})
})
// This code can be exported to another file
var utils = (function() {
function createMyElement(type, htmlString, params) {
var el = document.createElement(type);
if (htmlString)
el.innerHTML = htmlString;
addProps(el, params)
return el;
}
function addProps(el, props, key) {
if (Object.keys(props).length) {
for (var k in props) {
if (typeof(props[k]) === "object") {
addProps(el, props[k], k);
} else {
if (key) {
el[key][k] = props[k]
} else {
el[k] = props[k]
}
}
}
}
}
return {
createMyElement: createMyElement
}
})()
You can also try JSON based form.
Sample
JSFiddle
window.addEventListener('load', function() {
createPageSettingsPopup({
title: "foo"
})
})
function createPageSettingsPopup(page) {
var form = utils.createForm(getFormData(page))
document.body.appendChild(form)
}
// This can be stored in JSON file or in db and then can be fetched
function getFormData(page) {
var json = {
type: "div",
params: {
class: 'form-group',
innerHTML: "",
},
children: [{
type: 'label',
params: {
for: 'page-title',
innerHTML: "Title"
},
}, {
type: 'input',
params: {
type: 'text',
class: "form-control",
id: 'page-title',
value: page.title
}
}]
}
return json
}
// This is a generic utility and can be exported to a utility file
var utils = (function() {
function JSONBasedForm(form_json) {
var el = "";
if (form_json) {
el = createMyElement(form_json.type, form_json.params);
if (form_json.children && form_json.children.length > 0) {
form_json.children.forEach(function(child) {
var c_el = JSONBasedForm(child)
c_el && el.appendChild(c_el)
})
}
}
return el;
}
function createMyElement(type, params) {
var el = document.createElement(type);
addProps(el, params)
return el;
}
function addProps(el, props, key) {
if (Object.keys(props).length) {
for (var k in props) {
if (typeof(props[k]) === "object") {
addProps(el, props[k], k);
} else {
if (key) {
el[key][k] = props[k]
} else {
el[k] = props[k]
}
}
}
}
}
return {
createForm: JSONBasedForm
}
})()
This does not look better but is another way to create elements in JavaScript
Using the document.createElement you have more programmatic control over which attributes to set
function createPageSettingsPopup(page) {
var div = document.createElement("div");
div.className="form-group";
var label = document.createElement("label");
label.htmlFor="page-title";
label.textContent="Title";
var input = document.createElement("input");
input.type="text";
input.className="form-control";
input.id="page-title";
input.value=page.title;
label.appendChild(input);
div.appendChild(label);
return div;
}
Same in jQuery:
function createPageSettingsPopup(page) {
var $div = $("<div />",{"class":"form-group"});
$div.append(
$("<label />", {"htmlFor":"page-title").text("Title").append(
$("<input/>", { "type":"text","class":"form-control","id":"page-title"}).val(page.title)
)
);
return $div;
}

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>

Categories

Resources