Search code examples
javascriptjsonclient-side

How to read json file online client-side javascript


I have a JSON file on my website, and I want to access it from client-side vanilla javascript. How do I do that?

I don't want any HTML involved, like linking to the JSON file in the HTML and then accessing it via JavaScript. I need it to be in JavaScript and JSON, nothing else.


Solution

  • Replace URL with your JSON URL.You can use fetch to send request and receive response as a promise.

    // Replace URL with your url
    const url = "https://jsonplaceholder.typicode.com/todos/1";
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      })
      .catch((error) => {
        console.log(error);
      });

    Using Async-await

    async function getData(url) {
      try {
        const response = await fetch(url);
        const data = await response.json();
        console.log(data);
      } catch (error) {
        // Error handling here
        console.log(error);
      }
    }
    
    // Replace url with your url
    const url = "https://jsonplaceholder.typicode.com/todos/1";
    
    getData(url);