Tania Rascia Web Design and Development

Skip Navigation
How to Use JSON Data with PHP or JavaScript

How to Use JSON Data with PHP or JavaScript

/ 15 responses

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": "https://www.taniarascia.com"
}

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

What is JSON?

JSON stands for JavaScript Object Notation. It is data saved in a .json file, and consists of a series of key/value pairs.

{ "key": "value" }

The value of any JSON key can be a string, Boolean, number, null, array, or object. Comments are not allowed in JSON.

Although JSON resembles an object or an array, JSON is a string. A serialized string, which means it can later be parsed and decoded into data types.

Using data from JSON with PHP

First, to drill in that JSON is simply a string, we’re going to write JSON into a PHP string and apply it to a variable called $data.

$data = '{
	"name": "Aragorn",
	"race": "Human"
}';

Then we’ll use the json_decode() function to convert the JSON string into a PHP object.

$character = json_decode($data);

Now we can access it as a PHP object.

echo $character->name;

Here’s the whole file.

<?php

$data = '{
	"name": "Aragorn",
	"race": "Human"
}';

$character = json_decode($data);
echo $character->name;

Here is the output.

Aragorn

Accessing a JSON feed from a URL

From here out, we’ll put all JSON data into its own .json file. This way, we can retrieve the contents of the file instead of keeping it as a PHP string.

Here’s what data.json will look like.

[
	{
		"name": "Aragorn",
		"race": "Human"
	},	
	{
		"name": "Legolas",
		"race": "Elf"
	},
	{
		"name": "Gimli",
		"race": "Dwarf"
	}
]

And here’s how we’ll extract that data in 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 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 ($characters as $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 feed

echo $characters[0]->name;

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

We can display the data in a table, for an example.

<table>
	<tbody>
		<tr>
			<th>Name</th>
			<th>Race</th>
		</tr>
			<?php	
			foreach ($characters as $character) {
				echo '<tr>';
				echo '<td>' . $character->name . '</td>';
				echo '<td>' . $character->race . '</td>';
				echo '</tr>';
			}
			?>
	</tbody>
</table>
Name Race
Aragorn Human
Gimli Dwarf
Legolas Elf

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 ($characters as $character) {
	echo $character['race'] . '<br>';
}
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.

[
	{
		"name": "Harry Potter",
		"wand": [
			{
				"core": "phoenix feather",
				"length": "11 inches",
				"wood": "holly"
			}
		]
	},
	{
		"name": "Hermione Granger",
		"wand": [
			{
				"core": "dragon heartstring",
				"length": "10 and 3/4 inches",
				"wood": "vine"
			}
		]
	}
]

Decoding the feed.

$url = 'wizards.json'; 
$data = file_get_contents($url); 
$wizards = json_decode($data, true);

We’ll be able to access the nested array using $wizard['key'][0]['key'] in a loop, or whatever number corresponds correctly if you only want to print one.

foreach ($wizards as $wizard) {
	echo $wizard['name'] . '\'s wand is ' . 
			 $wizard['wand'][0]['wood'] . ', ' . 
		   $wizard['wand'][0]['length'] . ', with a ' . 
		   $wizard['wand'][0]['core'] . ' core. <br>' ;
}
Harry Potter's wand is holly, 11 inches, with a phoenix feather core. Hermione Granger's wand is vine, 10 and 3/4 inches, with a dragon heartstring core.

Converting a PHP object or array into JSON

Just as you use json_decode() to turn JSON into PHP, you can turn PHP into JSON with json_encode().

$data = [
	'name' => 'Aragorn',
	'race' => 'Human'
];

echo json_encode($data);

We made a PHP array and encoded it. Here’s the output:

{"name":"Aragorn","race":"Human"}

Using data from JSON with JavaScript

We’re going to create a JavaScript variable called data and apply the JSON string.

var data = '[ { "name": "Aragorn", "race": "Human" }, { "name": "Gimli", "race": "Dwarf" } ]'; 

Now we’ll use JavaScript built in JSON.parse() function to decode the string.

data = JSON.parse(data);

From here we can access the data like a regular JavaScript object.

console.log(data[1].name);
Gimli

And we can loop through each iteration with a for loop.

for (var i = 0; i < data.length; i++) {
	console.log(data[i].name + ' is a ' + data[i].race + '.');
}
Aragorn is a Human. Gimli is a Dwarf.

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 = new XMLHttpRequest();

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.

request.onload = function () {
	// begin accessing JSON data here
}

Then finally, submit the request.

request.send();

Here’s the final code.

var request = new XMLHttpRequest();

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

request.onload = function () {
	// begin accessing JSON data here
	var data = JSON.parse(this.response);

	for (var i = 0; i < data.length; i++) {
		console.log(data[i].name + ' is a ' + data[i].race + '.');
	}
}

request.send();

And the output.

Aragorn is a Human. Gimli is a Dwarf.

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.

$(document).ready(function () {
	$.getJSON('data.json', function (data) {
		// begin accessing JSON data here
			console.log(data[0].name);
	});
});

You might also see jQuery access JSON via an AJAX request, which is a little more verbose.

	$(document).ready(function () {
		var data;
		$.ajax({
			dataType: "json",
			url: 'data.json',
			data: data,
			success: function (data) {
				// begin accessing JSON data here
				console.log(data[0].name);
			}
		});
	});

Both will have the same output.

Aragorn

Conclusion

Hopefully this article has taught you a bit about what JSON is and does, and how to access JSON data with PHP, JavaScript, or jQuery.

Thank you for reading! I'm Tania Rascia, and I write no-nonsense guides for designers and developers. If my content has been valuable to you, please help me keep the site ad-free and continuously updated with quality tutorials and material by making a donation. Any amount helps and is greatly appreciated! Otherwise, let me know any ideas you have on a course you'd be eager to see.

Write a response

Your email address will not be published.

Discussion

  • dave says:

    Nice article! BTW How to execute edit and delete on json file with PHP code?

  • [email protected] says:

    Very nice explation. Thanks so much sister.

  • James says:

    Best explanation I’ve ever read. Love your site’s design as well. Thank you!!

  • Olubodun Agbalaya says:

    Bravo

  • Adrian says:

    “I can say that this is by far the most beginner friendly article I’ve ever read.”

    I agree !!!! thank you and congratulation for this .

  • Tig says:

    It’s cool but the Nested Array part has not been given a fair chance as the other parts.

  • Deepak says:

    I referred Eduonix blog to know more about php. But this tutorial is also very helpful to me as giving very good info about JASON data. Its very faster,lighter than XML on the wire data format. Please suggest me how to encoding JSON in PHP?

  • John says:

    Hi,
    Thx for the tutorial.
    I have an issue with an Open Data JSON API, it contains more than 2000 records to process. Each of the records contains also images (via url).
    When decoding to php, the data is loading quiet slow, in particular the images.
    Is there a trick to get the info faster?

  • Anon says:

    Really nice tutorial, many thanks.

    How could add an if statement, say I am looking only for data related to Gimli?

  • Anonymous says:

    Nice supereasy for beginners tutotial. I want to load json via ajax with the help of jQuery on “load more” button click (i. o. w. load more content without refreshng the page). Could this code ok?
    $(document).ready(function () {
    var data;
    $(‘#loadmore’).click(function(){
    $.ajax({
    dataType: “json”,
    url: ‘data.json’,
    data: data,
    success: function(html){
    $(“#content”).html(html);
    }
    });
    });

  • Hi Tania,
    Really dig these LOTR references, LOTR + Code = Awesomeness. Also found your CSS articles fun reading!

  • Mark Lee says:

    Before this tutorial, I didn’t know what JSON was.
    However, I followed this tutorial and worked great.
    Thank you so much for this tutorial.

  • Excellent sharing. Thank you so much.

  • Anonymous says:

    Nice! What about resultset (mysqli maybe) to json? Is there a direct way to convert or do we have to go resultset -> loop -> build phparray -> json_encode?

  • thinsoldier says:

    As someone who already struggled to learn this stuff 10 years ago I can say that this is by far the most beginner friendly article I’ve ever read.

Tania's List

My tutorials, guides, and articles for web designers, developers, and autodidacts, sent out once a month or so. No bullshit, ads, or tricks.