-2

I have a JSON file similar to the following:

[
  "thing1",
  "thing2",
  "thing3",
]

Let's call this file some-things.json.

I have a JavaScript file in the same directory as this JSON. I need the JSON data to be read in as an array, used elsewhere in the JavaScript.

What's the best way to do this? Do I have to read the JSON into a string and then parse to an array, or is there a nicer way? For example, array = ReadJSONArray('some-things.json').

I have looked for duplicates, but I haven't found any questions where the JSON is in a file, not a string.

Also, as stated in the question title, I don't want to use JQuery for this. I have seen a few questions on SO where people have asked this question, but tagged as and/or mentioning JQuery.

14
  • that does not look like a json Commented Sep 8, 2016 at 11:12
  • 1
    read this article, it may help you load the json file in your script: codepen.io/KryptoniteDove/post/… Commented Sep 8, 2016 at 11:14
  • @FlyingGambit care to elaborate? Commented Sep 8, 2016 at 11:14
  • @James — Try to parse it. See the syntax error. Commented Sep 8, 2016 at 11:16
  • this may help codepen.io/KryptoniteDove/post/… Commented Sep 8, 2016 at 11:17

2 Answers 2

-1

For reference, I solved this by using:

var array = require('./some-things.json');
Sign up to request clarification or add additional context in comments.

Comments

-3

Do I have to read the JSON into a string and then parse to an array…?

In general, yes.

XHR allows you to specify a response type of json, which lets you read the file over XHR and parse it in one go, but support is not universal.

Comments

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.