2

JSON.parse Syntax: JSON.parse(text[, reviver]) Parameters: text-The string to parse as JSON. reviver- Optional If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. Return value The Object corresponding to the given JSON text.

I really don't understand this. I have a JSON file that I need to use the data within to populate the DOM but I don't understand JSON.parse. When I tried to use this I used

var myData = JSON.parse({ "site": { "id": "example", "name": "example1" }...etc});

then tried to access it using dot notation.

console.log(myData.site.id);

I don't know what I'm doing, I've now figured out 200+ ways not to do it

1
  • 4
    What you do wrong is this: JSON is a string. Never anything else. You are not passing a string to JSON.parse() in your sample. Commented Dec 17, 2017 at 21:55

2 Answers 2

3

JSON.parse expects a JSON string as its parameter, but you are passing javascript object literal, which is an object already and does not need parsing.

Depending on your use case you can either add quotes to make the parameter string:

var myData = JSON.parse('{ "site": { "id": "example", "name": "example1" }}');

Or don't use JSON.parse at all and you can work with your object directly.

var myData = { "site": { "id": "example", "name": "example1" }};
Sign up to request clarification or add additional context in comments.

Comments

0

Pass JSON string to JSON.parse(yourJSONString) Then you can get values by call headers as follows.

var myRst = JSON.parse('{ "site": { "id": "example", "name": "example1" }}')

Then

myRst.site.id

    var myRst = JSON.parse('{ "site": { "id": "example", "name": "example1" }}')
    
    console.log(myRst.site.id)

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.