-2

Note : Using only pure JS, no addons, please provide a sample example

Sample data js file content -

var TABLE_DATA = [
  {
    "id": "5",
    "name": "cony #5",
    "thumbnailUrl": "image/5.gif",
    "price": 170
  },
  {
    "id": "1",
    "name": "cony #1",
    "thumbnailUrl": "image/1.gif",
    "price": 170
  },
  {
    "id": "2",
    "name": "cony #2",
    "thumbnailUrl": "image/2.gif",
    "price": 270
  },
  {
    "id": "8",
    "name": "cony #8",
    "thumbnailUrl": "image/8.gif",
    "price": 70
  },
  {
    "id": "10",
    "name": "<img onerror='window.document.body.innerHTML = \"<h1>XSS</h1>\";' src=''> ",
    "thumbnailUrl": "image/10.gif",
    "price": 170
  },
  {
    "id": "4",
    "name": "cony #4",
    "thumbnailUrl": "image/4.gif",
    "price": 150
  },
  {
    "id": "3",
    "name": "cony #3",
    "thumbnailUrl": "image/3.gif",
    "price": 130
  },
  {
    "id": "6",
    "name": "cony #6",
    "thumbnailUrl": "image/6.gif",
    "price": 160
  },
  {
    "id": "9",
    "name": "cony #9",
    "thumbnailUrl": "image/9.gif",
    "price": 170
  },
  {
    "id": "7",
    "name": "cony #7",
    "thumbnailUrl": "image/7.gif",
    "price": 170
  }
]
Addis
  • 2,480
  • 2
  • 13
  • 21

2 Answers2

2

js has inbuilt JSON.parse(YOUR_JSON_FILE) method for parsing json.

In your example it is a json array.

So you may use for loop to go through each individual jsons.

        const length = TABLE_DATA.length;
        for(var i =0 ;i< length;i++) {
            var jsObject = JSON.stringify(TABLE_DATA[i]);
            console.log(jsObject);
    //To read id 
    console.log(jsObject.id)
    //To read name
    console.log(jsObject.name)
    //and so on   
}

REMEMBER : JSON.parse turns a string of JSON text into a JavaScript object

JSON.stringify turns a JavaScript object into JSON text and stores that JSON text in a string

To LOAD_IN data from file click here : Loading Local Json File

May it Help You!

Abhishek Kumar
  • 820
  • 12
  • 16
1

To load your external file, it must be made available on some place that your script is able to access (e.g. a web server). If you place the data as pure JSON (without var TABLE_DATA), you can load this data using the XMLHttpRequest, something along the lines of the following:

const xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function() {
    if (this.readyState ==4  && this.status==200) { 
        data = JSON.parse(this.responseText)
        // do stuff with your data
    }
}
xhttp.open(URL_TO_THE_JSON)
xhttp.send()
Bart Barnard
  • 1,128
  • 8
  • 17