How to Use JSON Data with PHP or JavaScript

JSON is used to transmit data between a server and a browser. Here is a basic example of what might be in a .json string.

{"name":"Tania","title":"Web Developer","website":""}

As you can see, it's a human readable format of data that might traditionally be stored in a table. Some companies might have public .json files located that you can access and extract data from (an API you can connect to). You might also save a .json file somewhere in your project that you want to extract data from.

Goals

JSON data can be accessed and utilized with many programming languages. In this tutorial, we'll learn how to access JSON with PHP and JavaScript.

Prerequisites

You must either have a local server set up, or a host that runs PHP and some basic PHP knowledge.

$url='data.json';// path to your JSON file$data=file_get_contents($url);// put the contents of the file into a variable$characters=json_decode($data);// decode the JSON feed

In order to get one entry, we'll have to access the appropriate array number. Remember, counting begins with 0 in programming.

echo$characters[0]->name;

Aragorn

I can access all the data in the array with a foreach loop.

foreach($charactersas$character){echo$character->name.'<br>';}

Aragorn
Legolas
Gimli

Here is the full PHP file.

<?php$url='data.json';// path to your JSON file$data=file_get_contents($url);// put the contents of the file into a variable$characters=json_decode($data);// decode the JSON feedecho$characters[0]->name;foreach($charactersas$character){echo$character->name.'<br>';}

In this example, I'm using the alternate syntax for foreach, which looks like foreach() : /* loop */ endforeach; instead of foreach() { /* loop */ }. This is often preferable when outputting HTML.

Using associative arrays

There's another way we can access the data in PHP. If you pass true as the argument in json_decode(), the data becomes an associative array instead of an object. This means we'll be using square bracket notation[] instead of the skinny arrow->.

$characters=json_decode($data,true);// decode the JSON feed and make an associative array

Instead of ->race, we will access the value with ['race'].

echo$characters[0]['race'];

Human

And here's how to access the loop.

foreach($charactersas$character){echo$character['race']."\n";}

Human
Elf
Dwarf

Getting data from nested arrays

So far, we've only used JSON feeds with key/value pairs, but it's common to encounter nesting. Here's another nerdy example, which we can save in a new file called wizards.json.

That was easy! Now, we'll probably need to access JSON from a URL. There's an extra step involved, where we have to make a request to the file. Let's just take the above JSON string and put it in data.json.

;[{
name:'Aragorn',
race:'Human',},{
name:'Gimli',
race:'Dwarf',},]

Now we'll make an XMLHttpRequest().

var request =newXMLHttpRequest()

We'll open the file (data.json) via GET (URL) request.

request.open('GET','data.json',true)

From here, we'll parse and work with all our JSON data within the onload function.

Using Fetch

// Replace ./data.json with your JSON feedfetch('./data.json').then(response=>{return response.json()}).then(data=>{// Work with JSON data here
console.log(data)}).catch(err=>{// Do something for an error here})

Using jQuery

As you can see, it's not too difficult to retrieve a JSON feed with plain JavaScript. However, it's even easier with jQuery, using the getJSON() function. If you don't know how jQuery works, you'll need to load the jQuery JavaScript library before any of this custom code.

Conclusion

Join the newsletter

I write about JavaScript, programming, and front-end design. Join over 6,000 other developers in keeping up with my content. Unsubscribe whenever. Never any spam, ads, or affiliate links.

I'm Tania, a full-stack software developer specializing in modern JavaScript. I make
open source coding projects and write free, quality articles and tutorials that help
thousands of people daily. No ads, no sponsored posts, no bullshit.