user3508995
user3508995

Reputation: 187

JSON object not working when you use require in Nodejs

I have a JSON object in a server.js file as:

var stores = { 
              1: { "name": "a", "region": "vic" },
              2: { "name": "b", "region": "nsw" }
             };

But I want to put this into an external JSON file as it is a huge list and use:

var stores = require('./storeData.json');

so I can still have stores[1]["name"] = "a" But, I am getting an error of:

SyntaxError: /home/username/Documents/storeData.json: Unexpected token :
    at Object.parse (native)
    at Object.Module._extensions..json (module.js:486:27)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/home/username/Documents/server.js:18:14)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)

I can't figure out how the JSON should be structured for this to work.

Upvotes: 1

Views: 725

Answers (3)

nur farazi
nur farazi

Reputation: 1207

try to use json collection (widely used) . and you must quoted each key to be a string formate or it Will give error. or if you want to keep your formate too you can just go with this

{ 
"1": { "name": "a", "region": "vic" },
"2": { "name": "b", "region": "nsw" }
}

Upvotes: 0

Nir Levy
Nir Levy

Reputation: 12953

you are not allowed to use numbers as keys in json you can do something like this

var stores = { 
              "1": { "name": "a", "region": "vic" },
              "2": { "name": "b", "region": "nsw" }
             };

Upvotes: 0

Amadan
Amadan

Reputation: 198334

JSON is more specific than JS object syntax. In a JSON object representation, each key needs to be a string (and quoted):

{ 
  "1": { "name": "a", "region": "vic" },
  "2": { "name": "b", "region": "nsw" }
}

Upvotes: 2

Related Questions