How to push JS object to JSON in new line? - javascript

How modified this function to add every object in file's new line?
exports.addWaypoint = function(id, type, param){
var dataIn = fs.readFileSync('./markers.json');
var obj = JSON.parse(dataIn);
obj.markers.push({
"id": id,
"type": type,
"param": param,
});
writeJson(obj);
}

This may be a duplicate of Javascript: How to generate formatted easy-to-read JSON straight from an object?
Here's a quick answer: use JSON.stringify with an optional parameter to indicate the indention for each nested element.
var o = {
"id": 123,
"type": "good",
"param": { name: "Fred", age: 24 },
};
console.log( JSON.stringify(o,null,4) );

Related

How to convert JSON string having multiple rows to single row using javascript function

I have an output of REST API in following JSON format:
I need to convert the format to flat format so it can be passed as input to another API call.
{
"result": {
"data": [
{
"data": 2.824315071105957,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationForwardBrakingId" },
"controller": "ControllerNoneId",
"version": "00000000000363b0",
"id": "a5UyPzhknSC-N2wtLBph3BA"
},
{
"data": 0,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationSideToSideId" },
"controller": "ControllerNoneId",
"version": "00000000000363b1",
"id": "a5UyPzhknSC-N2wtLBph3BQ"
},
// ... 1000's of rows like this
]
}
}
I need to convert it in below format using a java-script
Desired format:
{"result":{ "data":[{"id":"b3","dateTime":"2019-09- 10T11:32:05.220Z","DiagnosticAccelerationSideToSideId":0,"DiagnosticAccelerationForwardBrakingId ":2.824315071105957},...
The rows needs to be merged with primary key as combination of ID and dateTime attributes. Please note the diagnostic id value becomes key for the required format and data value is the value of the key.
Is there any way to convert this JSON to above flat format.
Need to convert JSON having many rows for single data entry to single row format. Need one java-script function that can accept a string of rows format and convert or merge it and return the string in desired format
function String mergeRows(String flatDataJSONString) {
...
}
If the items are ordered (meaning i and i+1 are merged) than iterate with jumps of i += 2;
If its not ordered or the amount of items to be merged can be > 2 you use an object with unique key composed of the id and date, and override its data whenever a record match this key:
function merger (jsonStr) {
// convert str to obj
const jsonObj = JSON.parse(jsonStr);
const dataObj = {};
for (let i = 0; i < jsonObj.result.length; i++) {
const item = jsonObj.result[i];
// use unique key to merge by
const itemUniqueKey = item.device.id + item.dateTime;
// take last value or create empty object if not exists
const existingItem = dataObj[itemUniqueKey] || {};
// add some logic to merge item with existingItem as you need
...
// set the result back to dataObj to be used on next merges
dataObj[itemUniqueKey] = [merge result of item and existing item];
}
// take dataObj values, you don't need the keys any more
const dataArr = Object.values(dataObj);
const finalResult = {
result: {
data: dataArr
}
}
// convert back to json
return JSON.stringify(finalResult);
}
As stated in the comment you want first to have a clean json definition in order to stringify it. Please get to the following definition of your JSON first:
const json = {
"result": [
{
"data": 2.824315071105957,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationForwardBrakingId" },
"controller": "ControllerNoneId",
"version": "00000000000363b0",
"id": "a5UyPzhknSC-N2wtLBph3BA"
},
{
"data": 0,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationSideToSideId" },
"controller": "ControllerNoneId",
"version": "00000000000363b1",
"id": "a5UyPzhknSC-N2wtLBph3BQ"
}]
};
and then you will be able to perform like hereafter :
JSON.stringify(json)
Hope this helps !

Add data to end of ko.observablearray

I'm trying to add data to the end of an observable array but it's just not working as expected. I bet it is something minor but I just can't get my head around it.
What I am doing:
self.businesses = ko.observableArray();
function Business(business) {
var self = this;
self.BusinessID = ko.observable(business.BusinessID );
self.Type = ko.observable(business.Type);
self.Location = ko.observable(business.Location);
}
/*ajax get array of businesses as follows:
[
{
"$id": "1",
"BusinessID ": 62,
"Type": "Data",
"Location": "Data"
},
{
"$id": "2",
"BusinessID ": 63,
"Type": "Data",
"Location": "Data"
},
{
"$id": "3",
"BusinessID ": 64,
"Type": "Data",
"Location": "Data",
} ]
*/
var mappedBusinesses = $.map(data, function (business) { return new Business(business) });
self.businesses(mappedBusinesses);
This all works as expected and the obersablearray is populated.
However if I go to add another business, it wont work. For example, if I call the ajax that returns this (as newBusiness):
{
"$id": "1",
"BusinessID ": 68,
"Type": "Data",
"Location": "Data"
}
and I do:
self.businesses().push(newBusiness);
It adds to the array as an "Object" not a Business. So I thought I would do:
var bus = $.map(newBusiness, function (business) { return new Business(business) });
self.businesses().push(bus);
But I get the error in the JS console "Uncaught TypeError: Cannot read property 'BusinessID' of null
So I made a new var and added the brackets: [] in and it adds to the observable array but not as a "Business" object but rather as an "Array[1]" object at the end and this doesn't function as per the others. Code as follows:
var newBus = {
BusinessID: newBusiness.BusinessID,
Type: newBusiness.Type,
Location: newBusiness.Location
}
var bus = $.map(newBus, function (business) { return new Business(business) });
self.businesses().push(bus);
As mentioned this adds to the observable array but doesn't actually add as a "business" object but rather as an "array[1]" object.
I bet it's something so basic but just can't get it working!
Argh I knew it would be simple!
It was posting the whole array to the ObservableArray...not just the object.
The fix:
self.businesses.push(newBusiness[0])
Had to add the [0] in to get it to push the actual data into the array, not the object!
Thanks for the answers!
You're evaluating the array with your push:
self.businesses().push(newBusiness);
Observable Arrays have their own array functions, you should just do this (no parens):
self.businesses.push(newBusiness);
See this page: http://knockoutjs.com/documentation/observableArrays.html

Can a JSON array contain objects of different key/value pairs?

Can a JSON array contain Objects of different key/value pairs. From this tutorial, the example given for JSON array consists of Objects of the same key/value pair:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
If I want to change it to have different key/value pairs inside the JSON array, is the following still a valid JSON?
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
Just want to confirm this. If so, how can I use JavaScript to know if the JSON "example" field contains the first homogeneous objects or the second heterogeneous objects?
You can use any structure you like. JSON is not schema based in the way XML is often used and Javascript is not statically typed.
you can convert your JSON to a JS object using JSON.parse and then just test the existence of the property
var obj = JSON.parse(jsonString);
if(typeof obj.example[0].firstName != "undefined") {
//do something
}
It doesn't matter you can mix and match as much as you want.
You could just test it
typeof someItem.example !== 'undefined' // True if `example` is defined.
It's perfectly valid JSON. Personally I prefer this syntax better, because it reads easier:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
As to answer your second question, you can read data from a JSON string by using var data = JSON.parse(datastring);. Then simply use it by calling data.property.secondlevel. Any variable can be an object, array, string or number, allowing for nested structures.
You are free to do what you want with the contents of the array. Jus remember about this before you try to iterate an access properties of each item in your array.
one thing: you won't be able to deserialize this to anything else than an array of object in your server side, so don't have surprises later.
as a hint, maybe you could include a common field in the objects specifying the "type" so later is easy to process.
var array = [{"type":"fruit", "color":"red"},
{"type":"dog", "name":"Harry"}];
var parser = {
fruit:function(f){
console.log("fruit:" + f.color);
},
dog: function(d){
console.log("dog:"+d.name);
}};
for(var i=0;i<array.length;i++){
parser[array[i].type](array[i]);
}

document.getElementById and Value

I am new to Javascript and I would like to use the document.getElementById to show the value of items, in my example I would like to list the names printed in the var= btsFrontEnd ,but I am doing something wrong. Any help will be much appreciated.
Thank you.
Link to my Fiddle
var btsFrontEnd = {
"employee-1": {
"name": "Name One",
"phone": "1234567890",
"email": "blah#blah.com"
},
"employee-2": {
"name": "Name Two",
"phone": "1234567890",
"email": "blah#blah."
}
};
var btsemployees = {
employees:[
{
"name": "Name One",
"phone": "1234567890",
"email": "blah#blah.com"
},
{
"name": "Name Two",
"phone": "1234567890",
"email": "blah#blah.com"
},
{
"name": "Name Three",
"phone": "1234567890",
"email": "blah#blah.com"
},
{
"name": "Name Four",
"phone": "1234567890",
"email": "blah#blah.com"
},
{
"name": "Name Five",
"phone": "1234567890",
"email": "blah#blah.com"
}
]
};
//First argument is our data structure (an object or an array
//Second argument is a callback (logic we apply to our data structure)
$.each(btsFrontEnd, function (key, value) {
console.log(key); //Prints this object's keys
console.log(value); //Prints immediate values from this object
console.log(btsFrontEnd[key]);
console.log(value.name);
document.getElementById("names").innerHTML.value;// This is what I am referring to, I would like it to appear in the p id="names"
});
Here is the jsfiddle: http://jsfiddle.net/Ss2kk/7/
// Put names into an array
var employeeNames = [];
$.each(btsFrontEnd, function (employeeid, employee) { //first is the key or index, second argument is the value
// Check each element if it has name field
if (employee.name !== undefined) {
// Put its name into the array
employeeNames.push(employee.name);
}
});
// Join the array as comma seperated and put the content into `<p>` tag.
document.getElementById("names").innerHTML = employeeNames.join(",");
Inside your loop the key and value params represent the following values in the first iteration:
key
"employee-1"
value
Object { name="Name One", phone="1234567890", email="blah#blah.com"}
Since value is an object you can acces the name like this: value.name.
var names = document.getElementById( 'names' );
names.innerHTML = '';
$.each( btsFrontEnd, function( key, value ) {
names.innerHTML += value.name + '<br>';
});
All answers listed use jQuery, so I thought it'd be useful to add a pure javascript version. Two versions actually.
The first version uses Object.keys, which is relatively new compared to hasOwnProperty, which is used in the second version. This means the second version is compatible with more browsers.
Version 1:
// Declare variables
var keys, i, names = [];
// Get all keys in the btsFrontEnd object in an array. This is employee-1 and employee-2 in the example.
keys = Object.keys(btsFrontEnd);
// Loop over all keys
for(i = 0; i < keys.length; ++i) {
// Get the name of the employee via it's key and add it to the name array.
names.push(btsFrontEnd(keys[i]).name);
}
//Make one long string from the names with a comma as seperator, then put the string in the dom element.
document.getElementById("names").innerHTML = names.join(",");
Version 2:
// Declare variables
var key, names = [];
//Loop over all object properties
for(key in btsFrontEnd) {
// Check if the property is defined by you, and is not a standard Object property.
if(btsFrontEnd.hasOwnProperty(key)) {
names.push(btsFrontEnd[key].name);
}
}
//Make one long string from the names with a comma as seperator, then put the string in the dom element.
document.getElementById("names").innerHTML = names.join(",");

Loop over JSON items whether JSON object has multiple arrays or not

I have a working version of a function to loop through a single array in a JSON object, e.g.
[{
"Name": "John",
"Surname": "Johnson"
}, {
"Name": "Peter",
"Surname": "Johnson"
}]
sample function:
function FindName(NameToFind, data1) {
objData = JSON.parse(data1);
for (var i = 0; i < objData.length; i++) {
var Name = objData[i].Name;
if (Name == NameToFind) {
alert("found!");
}
}
}
Now I need to change this function to allow for either single OR multiple arrays e.g.
{
"Table1": [{
"Name": "John",
"Surname": "Johnson"
}, {
"Name": "Peter",
"Surname": "Johnson"
}],
"Table2": [{
"Name": "Sarah",
"Surname": "Parker"
},
{
"Name": "Jonah",
"Surname": "Hill"
}
]
}
Is there a way to determine whether the object has 1 array (like in first example) or more than one arrays (like in 2nd example), and any advice/guidance on how to extend the function to be able to loop through all the items whether it has 1 array or multiple arrays?
Your first object is an array, the second one isn't.
You can test if your argument is an array, or even just test
if (objData[0]) // that's an array
EDIT :
if you want to iterate over all properties of a (just json decoded) object, when it's not an array, you can do this :
for (var key in objData) {
var value = objData[key];
// now use the key and the value
// for example key = "Table1"
// and value = [{"Name":"John","Surname":"Johnson"}, ... ]
}

Categories

Resources