OiRc
OiRc

Reputation: 1622

Access JSON position in Node.js

I have a JSON string in this format:

[
   {
      "Origin":{
         "FtpHost":"info",
         "FtpFolder":"info",
         "FtpUser":"info",
         "FtpPassword":"info",
         "FtpInsideFolder":"info",
         "Pattern":"info"
      },
      "Destination":{
         "FtpHost":"info",
         "FtpFolder":"info",
         "FtpUser":"info",
         "FtpPassword":"info",
         "FtpInsideFolder":"info"
      },
      "CustomFolderName":"Conad",
      "OperationTraverseType":"RootOnly"
   }
]

To pick up the JSON I wrote this in Node.js:

var fs = require('fs');
var obj = fs.readFileSync('Operations.json', 'utf8');

I'm wondering, how I can access for example : "Destination" fields?

Upvotes: 0

Views: 278

Answers (3)

Gor
Gor

Reputation: 2908

You must parse this to JSON. because fs.readFile returns string

var fs = require('fs');
var obj = fs.readFileSync('Operations.json', 'utf8');
obj = JSON.parse(obj)

var Destination = obj[0].Destination
// or
var Destination = obj[0]["Destination"]

Edit (as said Diego)

You can also directly require json file

var obj = require('somejsonfile.json');
var Destination = obj[0]. Destination

Upvotes: 1

Arunkumar Kathirvel
Arunkumar Kathirvel

Reputation: 264

you can do like var myjson = JSON.parse(obj) or obj = JSON.parse(fs.readFileSync('Operations.json', 'utf8')) and then access it like obj[0]["Destination"]["FIELD"] where FIELD - represents the "Destination" object field you want

Upvotes: 1

Bidisha Pyne
Bidisha Pyne

Reputation: 541

Just need to simply parse the read data. Something like this:

var fs = require('fs');
var obj = fs.readFileSync('Operations.json', 'utf8').toString();
obj = JSON.parse(obj)
console.log(obj[0].Destination)

Upvotes: 1

Related Questions