Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JSON object Node.js [closed]

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?

like image 557
daniel the man Avatar asked Dec 20 '15 20:12

daniel the man


People also ask

How do you declare a JSON object 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.

How do I create a JSON object dynamically in node JS?

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.

What is toJSON () in JSON?

The toJSON() method returns a date object as a string, formatted as a JSON date.

How do you access JSON objects in Node JS?

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!


1 Answers

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"}]}' 
like image 192
paolobueno Avatar answered Sep 29 '22 16:09

paolobueno