I have been trying to add an element to a JSON array, in which the JSON array is designed with the following attributes:
/*
var courses = [{
"dept": "CSC",
"id": "3102",
"instructor": "Kooima",
"Location": "230 Turead"
}
]
and the JavaScript code segment that performs the task is implemented as:
var newCourse = {};
courses.push(newCourse);
var count = courses.length - 1;
courses[count].dept = dept;
courses[count].id = num;
courses[count].instructor = prof;
courses[count].Location = loc;
However, I believe this may not be in the correct order/missing further code to properly add the element to the list, and wanted to make sure I was possibly not neglecting an essential component.
What you did will work fine. Personaly I prefer the following way;
var newCourse = {};
newCourse.dept = dept;
newCourse.id = num;
newCourse.instructor = prof;
newCourse.Location = loc;
courses.push(newCourse);
There is nothing like JSON array, It's simple javascript array which you can create in the following manner.
Just push the new course every time
courses.push({
"dept": dept,
"id": id,
"instructor": prof,
"Location": loc
});
Quick and simple
courses.push({
"dept": dept,
"id": num,
"instructor": prof,
"Location": loc
});
Related
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.
$scope.partsLinesTest = data[0].instock; // this is getting the JSOn data
from my http request
for(var i=0; $scope.partsLinesTest.length > 0; i++) {
//$scope.partsLinesTest = $scope.partsLinesTest[0].instock;
console.log($scope.partsLinesTest.replace(/['{[\]}']/g,''))
var str = $scope.partsLinesTest;
$scope.partsLinesStock = str.replace(/['{[\]}']/g,'');
}
The Json data is somewhat formatted as below, my problem is with instock due to the extra regular brackets and curly braces which is why I thought using RegEX would solve problem, however I can't seem to iterate correctly through the data and post it back into the view, also I'm using Angular
var test = [
{
"id": 1,
"title": "This is a document",
"desc": "PO",
"date": "2017-01-15",
"instock": "[{'branch': 'Edmonton', 'quantity': 2}]"
}
A working temporary solution (no, better, a temporary workaround) would be to use Javascript's eval() function (which you should never do on a production system because it opens up security holes!):
var test = [
{
"id": 1,
"title": "This is a document",
"desc": "PO",
"date": "2017-01-15",
"instock": "[{'branch': 'Edmonton', 'quantity': 2}]"
}]
console.log(eval(test[0].instock))
console.log(Array.isArray(eval(test[0].instock)))
As #Quentin pointed out, the correct solution would be to make the server emit correctly formatted JSON (which would require replacing the single quotes ' by escaped double quotes \").
Please read about why using eval() is strongly discouraged: Why is using the JavaScript eval function a bad idea?
If it's JSON-esque you know it will have , and : dividing keys and values. I would start by cleaning out all other characters and splitting it on those:
var jsonString = "[{'branch': 'Edmonton', 'quantity': 2}]"
var cleaned = jsonString.replace(/[^a-zA-Z0-9:,]/g,'')
//"branch:Edmonton,quantity:2"
var splitIntoKeyVal = cleaned.split(',').map(function(row){ return row.split(':')})
//[["branch","Edmonton"],["quantity],2]]
var json = {}
splitIntoKeyVal.forEach(function(row){
json[row[0]] = row[1]
})
If you think your values might have : or , in them, you might have to do some other regex trickery.
In order to get the quantity you must parse the data.instock json.
var data = {
"id": 1,
"title": "This is a document",
"desc": "PO",
"date": "2017-01-15",
"instock": '[{"branch": "Edmonton", "quantity": 2}]'
};
var stock = JSON.parse(data.instock);
console.log(stock[0].quantity);
//$scope.partsLinesStock = stock[0].quantity;
I'm new to JSON and Jquery, and I can't find how to extract the values of ProjectCode from this JSON string.
[
{
"ProjectID": 3,
"CLustomerCode": "XYZ001",
"ProjectCode": "YZPROJ1",
"Description": "Project1",
"IssueManager": "iant",
"NotificationToggle": false,
"ProjectStatus": null,
"Added": "/Date(1400701295853}/",
"Added By": "iant",
"Changed": "/Date(1400701295853)/",
"Changed By": "iant"
},
{
"ProjectID": 4,
"CustomerCode": "XYZ001",
"ProjectCode": "XYXPROJ2",
"Description": "Projecton:Project2",
"IssweManager": "iant",
"NotificationToggle": false,
"Projectstatus": null,
"Added": "lDate(1400701317980)/",
"AddedBy": "iant",
"Changed": "/Date(1400701317980)/",
"Changed By": "iant"
}
]
The string above is from a variable called data that is the return value from stringify. I expected to be able to do something like
string proj = data[i].ProjectCode;
but intellisense doesn't include any of the properties.
I know very little about JSON - any help appreciated.
Thanks for reading.
Use parseJSON:
var obj = jQuery.parseJSON("{ 'name': 'Radiator' }");
alert(obj.name);
You need to loop through each object returned in the response and get the ProjectCode property inside each one. Assuming the data variable is your JSON this should work:
$.each(data, function(i, obj) {
console.log(obj.ProjectCode);
});
Use JSON.parse():
var a; // Your JSON string
var b = JSON.parse(a); //Your new JSON object
//You can access Project code, use index i in b[i].ProjectCode in a loop
var projectCode = b[0].ProjectCode;
You should post the raw code so its easier to visualize this stuff. Since what you are looking for is the list of ProjectCodes (in this case - ["XYZPROJ1", "XYZPROJ2"]).
It seems like what we have is an array or list ([...]) of projects. Where each project has a ProjectID, CustomerCode, ProjectCode, Description and so on...
So lets assume data points at this JSON blob. Here is how you would go about accessing the ProjectCode:
// Access the "i"th project code
var p_i_code = data[i].ProjectCode;
// How many projects?
var num_projects = data.length; // since data is a list of projects
// Want the list of project codes back? (I use underscore.js)
var project_codes = _.map(data, function(project) {
return project.ProjectCode;
});
I am working to fetch and analyze a large data set.
I want to know how many each value is appearing in the data set.
Let's give a small example to clarify things.
[
{"Year": "1997", "Company": "Ford", "Model": "E350", "Length": "2.34"},
{"Year": "2000", "Company": "Mercury", "Model": "Cougar", "Length": "2.38"}
{"Year": "2001", "Company": "Ford", "Model": "Cougar", "Length": "2.38"}
]
I don't know exactly what the values that I am having, but I want to hash it to get the results this way.
[
{"Value": "Ford", "Frequency": 2},
{"Value": "Mercury", "Frequency": 1},
]
In case it's not dynamic and I know the the values, I will do it this way:
var filteredCompany = data.filter(function(a) {
return /Ford/i.test(a.Company).lenght;
});
But, I have a very large data set (900 Mbo), I need to make this process in a very dynamic way.
UPDATE
var dataset = {}
d3.csv(link, function(data) {
dataset = data;
});
//Fetch data
var frequency = {};
var datasetlength = dataset.length;
for(var i = 0; i < datasetlength; i++){
var current = dataset[i];
if(!frequency.hasOwnProperty(current.company)) frequency[current.company] = 0;
frequency[current.company]++;
}
What you can do is loop through all the entries, and gather them into an object where the key is the name and the value is the count. The initial data will look like this:
{
"Ford" : 2,
"Mercury" : 1
}
You can do a reduce, passing through an object:
var frequency = hugeData.reduce(function(freq,current){
var currentCompany = current.Company;
if(!freq.hasOwnProperty(currentCompany)) freq[currentCompany] = 0;
freq[currentCompany]++;
return freq;
},{});
But reduce is ES5 and sometimes slow. You can do a plain loop:
var frequency = {};
var hugeDataLength = hugeData.length;
for(var i = 0; i < hugeDataLength; i++){
var current = hugeData[i];
var currentCompany = current.Company;
if(!frequency.hasOwnProperty(currentCompany)) frequency[currentCompany] = 0;
frequency[currentCompany]++;
}
Now that we have reduced the data into a much more manageable size, you can loop through the frequency data and turn it into an array, moving down the key and value into an object.
var chartData = Object.keys(frequency).map(function(company){
var value = frequency[company];
return {
Value : company,
Frequency : value
}
});
A running demo can be seen here.
I did a similar feat in the past few months, and your browser's debugger is a very handy tool for this job, especially the CPU profiler. You can pin down which operations are actually causing the lag.
I'm not sure if this is the most efficient method of going through that much data (then again, Javascript was not made for big data so efficiency shouldn't be on your mind).
Basically I would approach this looping through all the data with an associative array keeping track of the frequency. If the current data.Company is not in the associative array, it'll add it on to the array as a key and then input the frequency of one. If it is found as a key in the array, it'll increment the frequency by 1.
Example
[{"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;
}