Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I’m trying to get this JSON from my server:

JSON
[{"name":"Tie-Dye T-Shirt","type":"tie-dye","price":7.99},{"name":"Art1","type":"painting","price":13.99},{"name":"Hand-Made Bracelets","type":"braclet","price":5.99},{"name":"Pop-It","type":"pop-it","price":6.99},{"name":"Dimple","type":"dimple","price":7.99},{"name":"Stress Balls","type":"stress ball","price":3.99},{"name":"Mochis","type":"mochis","price":.50},{"name":"Snappers","type":"snapper","price":2.99},{"name":"Posters","type":"poster","price":5.99}]

…then parse and show it using this code:
JavaScript
var data = null
var xhttp = new XMLHttpRequest()
xhttp.onload = load
xhttp.open("GET", 'items.txt')
xhttp.send()

function load(){
  data = JSON.parse(xhttp.responseText) // error here

  setHtml()
}

function setHtml(){

  for (var i = 0; i < data.length; i++) {
    var e = document.createElement('div')
    e.innerHTML = '<h2>' + data[i].name + '</h2><h4>' + data[i].type + '</h4><p>' + data[i].price + '</p>'
    document.getElementById('stuff').appendChild(e)
  }
  
}


What I have tried:

I’ve tried alerting the type of the xhttp.responseText and xhttp.response to see if it was already parsed, it wasn’t. I also just locally defined the JSON and it worked fine. Mainly the problem is with the JSON.parse.
Posted
Updated 22-Mar-22 0:27am
Comments
Richard Deeming 22-Mar-22 5:13am    
If you want someone to help you fix an error in your code, then you need to tell us what that error is. Simply saying "error here" tells us precisely nothing!

Click the green "Improve question" link and update your question to include the full error details.

1 solution

I opened the dev tools in Chrome (Ctrl + Shift + I), took your JSON and in the console tab I tried to JSON.parse() the JSON content you provided and immediately the console told me what the issue was:
VM621:1 Uncaught SyntaxError: Unexpected token . in JSON at position 360
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

The issue seems to lie here: "price":.50 where the JSON isn't expecting a .50 but 0.50. Once you fix that the JSON should be parsed successfully.

Chrome dev tools
Mozilla dev tools
 
Share this answer
 
Comments
A-Games 22-Mar-22 8:57am    
thanks :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900