1

I have this json file I try to read using JS but it returns a syntax error: unexpected token at line 2 ":"

Where could this error come from?

   fetch('../json/destinations_data.json')
  .then(response => response.text())
  .then(data => {
    window.alert(data);
    console.log(data);
  });
{
    "user1":{
        "email":"[email protected]",
        "password":"oss117",
        "prenom":"Lucien",
        "nom":"Bramare"
    },
    "user2":{
        "email":"[email protected]",
        "password":"oss117",
        "prenom":"Noël",
        "nom":"Flantier"
    }
}

4 Answers 4

4

You're parsing it as text, not JSON.

   fetch('../json/destinations_data.json')
      .then(response => response.json()) //<-- do this!
      .then(data => {
          window.alert(data);
          console.log(data);
      });
Sign up to request clarification or add additional context in comments.

Comments

0

You are reading json file so instead of using response.text() use response.json()

   fetch('../json/destinations_data.json')
  .then(response => response.json())
  .then(data => {
    window.alert(data);
    console.log(data);
  });

Comments

0

There is a syntax error in your json file. You have to change your format. Please check https://www.w3schools.com/js/js_json.asp

users = [
    {
       "email":"[email protected]",
       "password":"oss117",
       "prenom":"Lucien",
       "nom":"Bramare"
   },
   {
       "email":"[email protected]",
       "password":"oss117",
       "prenom":"Noël",
       "nom":"Flantier"
    }
];

Comments

0

Try to parse it as json and not as text

replace this

  .then(response => response.text())

with this

  .then(response => response.json())

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.