1

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.

1
  • Put your json body in "jsonprettyprint.com" and see if it returns a proper json response or if it is returning null. I tried and it is returning null. Amadan's solution works, missing those quotes Commented Jun 20, 2017 at 17:17

3 Answers 3

2

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" }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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" }
             };

2 Comments

That is not JSON, that is JavaScript. And invalid JavaScript at that (JS does not allow for quotes in keys).
var stores = .. isn't valid JSON either.
0

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" }
}

2 Comments

this is wrong- it's redundant to change it to an array and changes the meaning (array is not the same as json object)
Not only is it 'redundant'.. but the end-effect is that it is invalid JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.