How to build this json? - javascript

[{"username" : "11"},
{"password" : "test"},
{"detailorder" : [
{"id" : "1",
"qty" : "5"},
{"id" : "2",
"qty" : "10"}
]}
]
How di I create above json in javascript? I have very low understanding in json. I reffered to How do i build JSON dynamically in javascript?. I need to add data dinamically especially for detailorder. But I' stuck from beginning.
I wrote
var datajson = [];
And i dont know how to what to write next. Sorry for my bad english. Thanks

Create the array, assign it to a variable and stringify it.
Here is how:
var arr = [
{ username:'11' },
{ password:'test' },
{ detilpesanan: [
{ id:'1',jumlah:'5' },
{ id:'2',jumlah:'10' }
]}
];
var json = JSON.stringify(arr);

do you mean like:
var datajson = [
{ "username" : 11 },
{"password" : "test"},
{"orderdetail" :
{
"id": 1,
"qty": 25
},
{
"id": 2,
"qty": 10
}
}
];
Added:
var datajson = {};
datajson.username = 11;
datajson.password = "test";
datajson.detilpesanan = [];
datajson.detilpesanan.push({});
datajson.detilpesanan.unshift({});
datajson.detilpesanan[0]["id"] = 1;
datajson.detilpesanan[0]["jumlah"] = 5;
datajson.detilpesanan[1]["id"] = 2;
datajson.detilpesanan[1]["jumlah"] = 10;
console.log( datajson );

I'd like to suggest something to make it easier. First, you will need to use jquery, or any other javascript library that provides json parsing and endcoding. Then create that structure as a standard object on javascript. Use jquery ( or whatever javascript library you chose ), to encode it into a JSON string for you.
I have been using JSON format for years now, but I can barely recall the need to write it down myself. Maybe there were instances, but I think I did not use it for the actual implementation.
You can also go to json.org, and download parsers and encoders available.
I hope that helped.

You can see: http://www.json.org/js.html
JSON (Javascrtip Serialization Object) is a serialization object type, so you cant create objects and then serialize this object, like this:
function createPerson()
{
var persons = new Array();
for(i=0; i<3; i++)
{
var details = new Array();
for(k = 0; k<2;k++)
{
var det = new persondetail(k,k*2);
details.push(det);
}
var p = new person('user'+i,'pdw'+i,details);
persons.push(p);
}
//-- serialize object, see console output
console.log(JSON.stringify(persons));
}
function person(user, pwd,det)
{
this.username = user;
this.password = pwd;
this.detilpesanan = det;
}
function persondetail(id, jumlah)
{
this.id = id;
this.jumlah = jumlah;
}

Related

Create a Listed (Nested) Element in a Javascript object

My question comes from this answer to a similar question. The comment below the answer sums up my question
how would the code look like if you would like to give depth to the tree? Like for name i would like to give name.firstname and name.lastname. Would I need to define name as var?
This is my current code
var jsonOutput = new Object();;
jsonOutput.workflowID=1234;
jsonOutput.author="jonny"
I want to create a javascript object that looks like the below. I am stuck with creating the list of Tools. How would I do this?
{
"workflowID": "1234",
"author": "jonny",
"tools": [
{
"toolid": "543",
"type": "input",
},
{
"toolid": "3423",
"type": "input",
},
{
"toolid": "1234",
"type": "merge",
"on": "Channel Name"
}
]
}
Create a data object
Populate the inner hierarchy with values
Add a tools array to data
Create tool object and populate
Push tool to the tools array
Repeat
var data = {};
data.workflowID = 1234;
data.author = "jonny";
data.tools = [];
let tool = {};
tool.toolid = 543;
tool.type = "input";
data.tools.push(tool);
tool = {};
tool.toolid = 3423;
tool.type = "input";
data.tools.push(tool);
tool = {};
tool.toolid = "1234";
tool.type = "merge";
tool.on = "Channel Name";
data.tools.push(tool);
console.log(data);
Technically, to create a more complex object, you can just do something like:
tool543 = new Object();
tool543.toolid = "543";
tool543.type = "input";
jsonOutput.tools = []; // Now .tools is an empty array
jsonOutput.tools.push(tool543); // And now you're appending to it.

How to reformat data in objects. (How can i make the rows the Keys and other columns the values)

I have been able to export data from google sheets into a pretty awesome JSON file, just not in the format I need (oops:) ).
Basically, I have data where the column name is the value header (in this case: location, infected, deaths, recovered, etc.) and row name are the values respectively.
Is there a way I can reformat this into multiple objects so I have:
var death_data = {
cn: "132",
th: "0",
mo: "0",
au: "0",
sg: "0",
};
var infected_data = {
cn: "4415",
th: "8",
mo: "7",
au: "5",
sg: "5",
};
(The 2 letters are the Country Codes. CN: 3554+277+296+..other china values+...152+108+84...+13+6.)(132=125+2+1+1+1+1+1)
I found a similar resource here, however it is in R. Is there a similar method for JavaScript?
In case your wondering how I have tried to generate the objects:
function doGet() {
var result = {};
var infected = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data').getDataRange().getValues();
var death = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data').getDataRange().getValues();
result = makeObject(infected);
// result.death = makeObject(death);
//Logger.log(result);
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType.JSON);
}
function makeObject(multiArr) {
var obj = {};
var headers = multiArr.shift();
for(var i = 0; i < headers.length; i++){
obj[headers[i]] = multiArr.map(function(app) {
return app[i];
});
}
return obj;
}
Using the above code, the JSON looks like this (Using JSON Viewer chrome extension):
Where each key then has values, like this:
and this
Maybe there is a better way than trying to convert the formats after the fact, and instead just generate them correctly the first time.
Sorry in advance for my basic knowledge of JavaScript, i'm just getting started.
Any help would be greatly appreciated.
Kind Regards,
Camden
You could create such a object by looping over the array and adding relevant values:
Sample script:
function makeObject(multiArr) {
var obj = {deaths:{}, infected:{}};
var headers = multiArr.shift();
multiArr.forEach(function(row){
var [_,country,_,infected,deaths,_] = row;
obj.deaths[country] = obj.deaths[country] || 0;
obj.infected[country] = obj.infected[country] || 0;
obj.deaths[country] = obj.deaths[country] + Number(deaths);
obj.infected[country] = obj.infected[country] + Number(infected);
})
return obj;
}

JS converting an array to a json linked list?

I am new to JS and the concepts of organising data elude me a little, trying to take data from a specific array format (as this is what I have to work with) and output it into another specific JSON format.
This is to pass data to the D3 sankey module
https://github.com/d3/d3-plugins/blob/master/sankey/sankey.js
I can't figure out is how to add the index of the node into the links, rather than the name.
Really I am just totally lost with it!
I made a fiddle here:
https://jsfiddle.net/adamdavi3s/kw3jtzx4/
Below is an example of the data and the output required
var data= [
{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var output= {
"nodes":[
{"name":"Agricultural 'waste'"},
{"name":"Bio-conversion"},
{"name":"Electricity grid"},
{"name":"Losses"},
{"name":"Liquid"}
],
"links":[
{"source":0,"target":1,"value":124.729},
{"source":1,"target":2,"value":0.597},
{"source":1,"target":3,"value":26.862},
{"source":1,"target":4,"value":280.322},
{"source":3,"target":4,"value":280.322}
]
};
Here is my code from the fiddle thusfar
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source};
var found = jQuery.inArray(node, sourceArray);
if (found < 0) {
// Element was not found, add it.
sourceArray.push(node);
}
}
console.log(sourceArray);
In javascript:
[ ] annotations are used to describe an Array, like:
var names=["John","Lisa"]
{ } Its are used to describe an Object
var person = {"name" : "John", "age" : 23}
You can use them inside one another
var people=[{"name" : "John", "age" : 23},{"name" : "Lisa", "age" : 44}]
Try this:
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
var linkArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source,};
var link= {
"source":i,
"target":data[i].target,
"value":data[i].value,
};
var found = jQuery.inArray(node, sourceArray);
if (found >= 0) {
// Element was found, remove it.
sourceArray.splice(found, 1);
linkArray.splice(found, 1);
} else {
// Element was not found, add it.
sourceArray.push(node);
linkArray.push(link);
}
}
finalArray={"nodes": sourceArray,"links": linkArray}
console.log(finalArray);
https://jsfiddle.net/9x4rdyy7/
Array.reduce() is perfect for this use case ;)
Take a look.
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var output = data.reduce(function(result, item){
for(key in search = ['source','target']) {
var value = item[search[key]];
if(! result.index.hasOwnProperty(value)){
result.index[value] = Object.keys(result.index).length;
result.nodes.push({name: value});
}
}
result.links.push({
source: result.index[item.source],
target: result.index[item.target],
value: Number(item.value)
});
return result;
}, {nodes: [], links: [], index: {}});
delete output.index;
console.log(output);

JSON parsing using jQuery is not working

I have a JSON which is like this-
var json = {
"http://data.abc.net/uml/extensions#0001" : {
"http://www.w3.org/2000/01/rdf-schema#label" : [ {
"type" : "literal" ,
"location" : "ASIA" ,
"datatype" : "http://www.w3.org/2001/XMLSchema#string"
}]
}
,
"http://data.abc.net/uml/extensions#0002" : {
"http://www.w3.org/2000/01/rdf-schema#label" : [ {
"type" : "literal" ,
"location" : "EUROPE" ,
"datatype" : "http://www.w3.org/2001/XMLSchema#string"
}]
}
}
I am trying to parse this using JQUERY and want to store the values ASIA and EUROPE in an array called allREgions. I have written a code like this-
var allRegions = [];
var output = $.parseJSON(json);
var list = output.data;
$.each(list,function(index, val){
allRegions.push(val.location);
});
But this is not working. What is going wrong in here?
Your first problem is that you do not have JSON. You have a JavaScript object literal. You don't need to parse it (because parsing JSON converts JSON into an object), and trying to do so will first convert it to a string (which wouldn't be valid JSON).
Replace var output = $.parseJSON(json); with var output = json;.
Your second problem is that you don't have a data property in the object. Your properties are http://data.abc.net/cib/cia/uml/extensions#0001 and http://data.abc.net/cib/cia/uml/extensions#0002
Replace var list = output.data; with var list = output.
You can skip both those steps and just apply the data to the right thing in the first place.
Your third problem is that when you loop over them, your values are objects with one property (http://www.w3.org/2000/01/rdf-schema#label) so you can't access location.
To get to that you have to read the value of that property, then get the first index of the array that its value is, and then access the location of that.
var data = {
"http://data.abc.net/cib/cia/uml/extensions#0001": {
"http://www.w3.org/2000/01/rdf-schema#label": [
{
"type": "literal",
"location": "ASIA",
"datatype": "http://www.w3.org/2001/XMLSchema#string"
}
]
},
"http://data.abc.net/cib/cia/uml/extensions#0002": {
"http://www.w3.org/2000/01/rdf-schema#label": [
{
"type": "literal",
"location": "EUROPE",
"datatype": "http://www.w3.org/2001/XMLSchema#string"
}
]
}
}
var allRegions = [];
$.each(data,function(index, val){
allRegions.push(val['http://www.w3.org/2000/01/rdf-schema#label'][0].location);
});
you dont need to use $.parseJSON, just do:
var allRegions = [];
$.each(json, function(idx, val) {
$.each(val, function(idxSec, valSec) {
allRegions.push(valSec[0].location);
});
});
console.log(allRegions);
jsFiddle demo

creating list of objects in Javascript

Is it possible to do create a list of your own objects in Javascript? This is the type of data I want to store :
Date : 12/1/2011 Reading : 3 ID : 20055
Date : 13/1/2011 Reading : 5 ID : 20053
Date : 14/1/2011 Reading : 6 ID : 45652
var list = [
{ date: '12/1/2011', reading: 3, id: 20055 },
{ date: '13/1/2011', reading: 5, id: 20053 },
{ date: '14/1/2011', reading: 6, id: 45652 }
];
and then access it:
alert(list[1].date);
dynamically build list of objects
var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
listOfObjects.push(singleObj);
});
here's a working example http://jsfiddle.net/b9f6Q/2/
see console for output
Maybe you can create an array like this:
var myList = new Array();
myList.push('Hello');
myList.push('bye');
for (var i = 0; i < myList .length; i ++ ){
window.console.log(myList[i]);
}
Going off of tbradley22's answer, but using .map instead:
var a = ["car", "bike", "scooter"];
a.map(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
return singleObj;
});
Instantiate the array
list = new Array()
push non-undefined value to the list
var text = list.forEach(function(currentValue, currentIndex, listObj) {
if(currentValue.text !== undefined)
{list.push(currentValue.text)}
});
So, I'm used to using
var nameOfList = new List("objectName", "objectName", "objectName")
This is how it works for me but might be different for you, I recommend to watch some Unity Tutorials on the Scripting API.

Categories

Resources