Working with JSON in JavaScript: From Local Files to API Responses

Discover how to read and parse JSON in JavaScript, with use cases from real-world web scraping. Includes tips, code examples, and datasets from Infatica.

Working with JSON in JavaScript: From Local Files to API Responses
Denis Kryukov
Denis Kryukov 6 min read
Article content
  1. What Is JSON?
  2. Reading JSON in JavaScript
  3. Practical Use Case: Displaying Dataset Contents
  4. Common Pitfalls and Debugging Tips
  5. Frequently Asked Questions

JSON (JavaScript Object Notation) is the most common data format used for storing and exchanging structured information on the web. Whether you're building a frontend dashboard, working with APIs, or processing scraped datasets, chances are you'll encounter JSON daily. In this guide, we’ll walk through the most practical ways to read and work with JSON files in JavaScript.

What Is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format based on a subset of JavaScript’s object syntax. Despite its roots in JavaScript, JSON is language-independent and widely supported across modern programming environments.

A JSON file typically consists of key-value pairs, much like JavaScript objects, and can represent data structures such as arrays, nested objects, strings, numbers, and booleans. Here's a simple example of JSON representing a product:

{
  "id": 1024,
  "name": "Wireless Mouse",
  "price": 19.99,
  "inStock": true,
  "categories": ["electronics", "accessories"]
}

What makes JSON so powerful is its simplicity and flexibility – it’s easy for machines to parse and for humans to read. That’s why it has become the standard for APIs, configuration files, and data delivery formats.

Different types of data formats

For example, many of Infatica’s clients receive datasets in JSON when extracting structured data from e-commerce sites, travel platforms, or search engines. This makes it easy to process, visualize, or feed directly into applications without additional conversion steps.

The Smarter Way to Access Web Data: Pre-Built Datasets
Infatica provides scalable, high-quality datasets from trusted sources – ideal for market research, pricing intelligence, and more.

Reading JSON in JavaScript

Whether you’re working in a browser or a server-side environment like Node.js, JavaScript provides intuitive ways to read and handle JSON. Let’s take a closer look at the most common scenarios you’ll encounter:

Reading Static JSON Files (Client-Side)

If you're working on a web application and want to load a local or remote JSON file, the fetch() API is your go-to tool:

<script>
  fetch('data/sample.json')
    .then(response => response.json())
    .then(data => {
      console.log('Data loaded:', data);
    })
    .catch(error => {
      console.error('Error loading JSON:', error);
    });
</script>

This approach is great for static files included in your project or JSON hosted on a public server. Keep in mind that due to CORS policies, loading local files may require a development server.

Reading JSON from an API

When working with APIs, JSON is the most common response format. You can use the same fetch() method to retrieve and parse data:

async function loadWeather() {
  const response = await fetch('https://api.example.com/weather');
  const json = await response.json();
  console.log(json);
}
loadWeather();

At Infatica, our scraping APIs deliver data in a similar format – optimized for quick parsing and integration into dashboards, CRMs, or data pipelines.

Reading JSON Files in Node.js

In Node.js, you have a few options to read local JSON files:

A. Using fs.readFile():

const fs = require('fs');

fs.readFile('./data/sample.json', 'utf8', (err, data) => {
  if (err) throw err;
  const jsonData = JSON.parse(data);
  console.log(jsonData);
});

B. Using require() (synchronous, cached):

const data = require('./data/sample.json');
console.log(data);

Note: This method only works for static, local JSON files and is best suited for configuration files or seed data.

Parsing JSON Strings

Sometimes you may receive a raw JSON string from an API or file and need to convert it into a JavaScript object.

const jsonString = '{"product":"laptop","price":1499}';
const parsedData = JSON.parse(jsonString);
console.log(parsedData.price); // 1499

To convert a JavaScript object back into a JSON string (e.g., for storage or transmission), use JSON.stringify():

const obj = { city: 'Berlin', temperature: 22 };
const stringified = JSON.stringify(obj);
console.log(stringified);

Tip for Developers

Make sure the JSON you're reading is valid. Even a missing quote or extra comma can cause a parsing error. Tools like JSONLint can help you validate the structure before importing it.

Practical Use Case: Displaying Dataset Contents

Let’s walk through a practical example of how JSON data can be loaded and used in a real-world scenario. This will help you understand how developers typically consume scraped or structured datasets – just like those offered by Infatica.

Suppose you've received a dataset containing hotel prices in JSON format. This is a common use case for businesses that analyze regional pricing trends or competitors across booking platforms. Here’s a simplified version of what that JSON might look like:

[
  {
    "hotel": "Hotel Catalonia",
    "location": "Barcelona",
    "price": 129,
    "currency": "EUR"
  },
  {
    "hotel": "NH Collection Gran Hotel",
    "location": "Barcelona",
    "price": 155,
    "currency": "EUR"
  }
]

Step-by-Step: Load and Display in a Web App

Here’s how you might load and display this data using JavaScript in a web page:

<!DOCTYPE html>
<html>
<head>
  <title>Hotel Prices</title>
</head>
<body>
  <h2>Hotel Prices in Barcelona</h2>
  <ul id="hotel-list"></ul>

  <script>
    fetch('data/hotel_prices.json')
      .then(response => response.json())
      .then(data => {
        const list = document.getElementById('hotel-list');
        data.forEach(hotel => {
          const item = document.createElement('li');
          item.textContent = `${hotel.hotel} – ${hotel.price} ${hotel.currency}`;
          list.appendChild(item);
        });
      })
      .catch(error => {
        console.error('Failed to load data:', error);
      });
  </script>
</body>
</html>

This HTML+JS example fetches the hotel pricing JSON from a local file, parses and loops through the array of hotel objects, and renders the results into the page dynamically.

💡 At Infatica, clients often use similar scripts to visualize or filter live data coming from our scraping API – whether it's hotel rates, e-commerce prices, or keyword search results.

Common Pitfalls and Debugging Tips

Working with JSON in JavaScript is usually straightforward – but a few common mistakes can lead to frustrating bugs. This chapter outlines the most frequent issues developers face when reading or parsing JSON data, along with quick fixes to keep your code error-free.

Invalid JSON Format

Unlike JavaScript objects, JSON has strict syntax rules:

  • Keys and strings must be wrapped in double quotes ('')
  • No trailing commas
  • No comments or functions allowed

Invalid JSON:

{
  hotel: "Miramar", // missing quotes around key and has a comment
  price: 120,
}

Valid JSON:

{
  "hotel": "Miramar",
  "price": 120
}

Forgetting to Parse the Response

If you're using fetch() to get JSON from an API and forget to call .json(), you'll be dealing with a raw Response object – not the actual data.

Incorrect:

const data = fetch('/api/data.json');
console.log(data); // [object Promise]

Correct:

const response = await fetch('/api/data.json');
const data = await response.json();

Mixing Up JSON.parse() and JSON.stringify()

Use JSON.parse() to convert a JSON string into a JavaScript object. Use JSON.stringify() to convert a JavaScript object into a JSON string. For example:

const jsonStr = '{"name":"Infatica","type":"Scraping Service"}';
const obj = JSON.parse(jsonStr); // → JavaScript object

const backToJson = JSON.stringify(obj); // → JSON string

If you try to parse an object or stringify a string twice, you may end up with confusing results or errors.

Handling Asynchronous Code Incorrectly

If you're using fetch() or fs.readFile() in Node.js, remember they’re asynchronous. If you try to use the result immediately, it may still be undefined.

  • Use async/await with try/catch blocks
  • Or properly chain .then() and .catch() in promise-based code

Overlooking CORS and File Access Issues

When loading JSON files in a browser, you may run into issues like:

  • CORS restrictions when accessing a remote resource
  • File access errors when loading a local file directly via file://

Solution: Use a local development server (e.g., Live Server in VS Code or http-server in Node.js) to serve local files over HTTP.

Frequently Asked Questions

Use the fetch() API in the browser or fs.readFile() in Node.js to load the file, then parse it using response.json() or JSON.parse(). JSON integrates natively into most JavaScript environments.

JSON is lightweight, human-readable, and supports complex data structures – making it ideal for exporting scraped data. At Infatica, we use JSON as the default format for datasets delivered via our scraping APIs.

Due to browser security restrictions, local files often require a local development server (e.g., http-server or Live Server in VS Code). You can’t load file:// JSON directly via fetch().

JSON.parse() converts a JSON string into a JavaScript object. JSON.stringify() does the reverse – turning a JavaScript object into a JSON string for storage or transmission.

Ensure your JSON is valid – check for proper quotes, no trailing commas, and correct nesting. Use try/catch in JavaScript or tools like JSONLint to validate data, especially when consuming scraped datasets.

Denis Kryukov

Denis Kryukov is using his data journalism skills to document how liberal arts and technology intertwine and change our society

You can also learn more about:

Working with JSON in JavaScript: From Local Files to API Responses
Web scraping
Working with JSON in JavaScript: From Local Files to API Responses

Discover how to read and parse JSON in JavaScript, with use cases from real-world web scraping. Includes tips, code examples, and datasets from Infatica.

How to Use Proxies for Data Collection (The Simple Way)
Proxies and business
How to Use Proxies for Data Collection (The Simple Way)

Learn how to use proxies to collect data more effectively and securely. This guide walks you through picking the right type of proxy, setting it up, and following best practices to ensure your data gathering process is smooth, safe, and within legal boundaries.

What’s New: Smarter, Faster, and More Secure Web Scraping
Infatica updates
What’s New: Smarter, Faster, and More Secure Web Scraping

Stay ahead of web scraping challenges with our improved scraper – featuring real-time JavaScript rendering, streamlined API key usage, anti-detect upgrades, and enhanced infrastructure capacity.

Get In Touch
Have a question about Infatica? Get in touch with our experts to learn how we can help.