read a json file in javascript

To read a JSON file in JavaScript, you can use the built-in XMLHttpRequest object to make a request to the JSON file and then parse the response as JSON.

Here's an example code snippet:

index.tsx
let request = new XMLHttpRequest();
request.open("GET", "example.json", false);
request.send();
let jsonData = JSON.parse(request.responseText);
145 chars
5 lines

In this example, the XMLHttpRequest object is used to make a GET request to the "example.json" file. The response is then parsed as JSON using the JSON.parse() method and stored in the jsonData variable.

Note: XMLHttpRequest should not be used for new code, instead fetch() should be used to make requests.

index.tsx
fetch('example.json')
  .then(response => response.json())
  .then(data => console.log(data));
95 chars
4 lines

This code first calls the fetch() method with the URL of the JSON file. The response is then parsed as JSON using the response.json() method and the resulting data is logged to the console.

related categories

gistlibby LogSnag