I am trying to create a JSON object in Node.js without any success. For example an object like this:
{ 'Orientation Sensor': [ { sampleTime: '1450632410296', data: '76.36731:3.4651554:0.5665419' }, { sampleTime: '1450632410296', data: '78.15431:0.5247617:-0.20050584' } ], 'Screen Orientation Sensor': [ { sampleTime: '1450632410296', data: '255.0:-1.0:0.0' } ], 'MPU6500 Gyroscope sensor UnCalibrated': [ { sampleTime: '1450632410296', data: '-0.05006743:-0.013848438:-0.0063915867}, { sampleTime: '1450632410296', data: '-0.051132694:-0.0127831735:-0.003325345'}]}
but in a dynamic way without any knowledge about the size of every item. Is there something like that in Node.js?
nodejs-write-json-object-to-file.js log(jsonObj); // stringify JSON Object var jsonContent = JSON. stringify(jsonObj); console. log(jsonContent); fs. writeFile("output.
To create JSON object dynamically via JavaScript, we can create the object we want. Then we call JSON. stringify to convert the object into a JSON string. let sitePersonnel = {}; let employees = []; sitePersonnel.
The toJSON() method returns a date object as a string, formatted as a JSON date.
Read JSON From File System In NodeJS:var jsonObj = require( "./path/to/myjsonfile. json" ); Here, NodeJS automatically read the file, parse the content to a JSON object and assigns that to the left hand side variable. It's as simple as that!
What I believe you're looking for is a way to work with arrays as object values:
var o = {} // empty Object var key = 'Orientation Sensor'; o[key] = []; // empty Array, which you can push() values into var data = { sampleTime: '1450632410296', data: '76.36731:3.4651554:0.5665419' }; var data2 = { sampleTime: '1450632410296', data: '78.15431:0.5247617:-0.20050584' }; o[key].push(data); o[key].push(data2);
This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify
:
JSON.stringify(o); //> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With