JSON Tutorial: Request API Data with JavaScript or PHP
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.
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.
- You must either have a local server set up, or a host that runs PHP and some basic PHP knowledge.
- Basic knowledge of programming concepts (arrays and variables) and using JavaScript.
JSON stands for JavaScript Object Notation. It is data saved in a .json file, and consists of a series of key/value pairs.
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 .
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.
$data = '< "name": "Aragorn", "race": "Human" >'; $character = json_decode($data); echo $character->name;
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.
I can access all the data in the array with a foreach loop.
foreach ($characters as $character) echo $character->name . '
'; >
Here is the full PHP file.
$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 . '
'; >
We can display the data in a table, for an example.
table> tbody> tr> th>Nameth> th>Raceth> tr> foreach ($characters as $character) : ?> tr> td> echo $character->name; ?> td> td> echo $character->race; ?> td> tr> endforeach; ?> tbody> table>
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.
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’] .
And here’s how to access the loop.
foreach ($characters as $character) echo $character['race'] . "\n"; >
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" > ] > ]
$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.
' ; >
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:
Using data from JSON with JavaScript
We’re going to create a JavaScript variable called data and apply the JSON string.
Now we’ll use JavaScript built in JSON.parse() function to decode the string.
From here we can access the data like a regular JavaScript object.
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.
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()
Aragorn is a Human. Gimli is a Dwarf.
Now you can also use the Fetch API to do the same thing. Read How to use the JavaScript Fetch API to Get JSON Data for an easier method to get this data.
// Replace ./data.json with your JSON feed fetch('./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 >)
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.
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.
Newsletter
If you liked this post, sign up to get updates in your email when I write something new! No spam ever.
Comments
About me
Hello and thanks for visiting! My name is Tania Rascia, and this is my website and digital garden. 🌱
I’m a software developer who creates open-source projects and writes about code, design, and life. This site is and has always been free of ads, trackers, social media, affiliates, and sponsored posts.
Post Details
Category
Tags
Newsletter
Get updates when I write something new! No spam, I respect your inbox.
Работа с JSON в PHP
JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар . Значение может быть массивом, числом, строкой и булевым значением.
В PHP поддержка JSON появилась с версии 5.2.0 и работает только с кодировкой UTF-8.
Кодирование
json_encode($value, $options) – кодирует массив или объект в JSON.
$array = array( '1' => 'Значение 1', '2' => 'Значение 2', '3' => 'Значение 3', '4' => 'Значение 4', '5' => 'Значение 5' ); $json = json_encode($array); echo $json;
Как видно кириллица кодируется, исправляется это добавлением опции JSON_UNESCAPED_UNICODE .
$json = json_encode($array, JSON_UNESCAPED_UNICODE); echo $json;
Далее такую строку можно сохранить в файл, или отдать в браузер, например при AJAX запросах.
header('Content-Type: application/json'); echo $json; exit();
Декодирование
Функция json_decode($json) преобразует строку в объект:
$json = ''; $array = json_decode($json); print_r($array);
stdClass Object ( [1] => Значение 1 [2] => Значение 2 [3] => Значение 3 [4] => Значение 4 [5] => Значение 5 )
Если добавить вторым аргументом true , то произойдёт преобразование в массив:
$json = ''; $array = json_decode($json, true); print_r($array);
Array ( [1] => Значение 1 [2] => Значение 2 [3] => Значение 3 [4] => Значение 4 [5] => Значение 5 )
Получение ошибок и их исправление
json_decode() возвращает NULL , если в объекте есть ошибки, посмотреть их можно с помощью функции json_last_error() :
$json = ''; $array = json_decode($json, true); switch (json_last_error())
Посмотреть значения констант JSON:
$constants = get_defined_constants(true); foreach ($constants['json'] as $name => $value) < echo $name . ': ' . $value . '
'; >
JSON_HEX_TAG: 1 JSON_HEX_AMP: 2 JSON_HEX_APOS: 4 JSON_HEX_QUOT: 8 JSON_FORCE_OBJECT: 16 JSON_NUMERIC_CHECK: 32 JSON_UNESCAPED_SLASHES: 64 JSON_PRETTY_PRINT: 128 JSON_UNESCAPED_UNICODE: 256 JSON_PARTIAL_OUTPUT_ON_ERROR: 512 JSON_PRESERVE_ZERO_FRACTION: 1024 JSON_UNESCAPED_LINE_TERMINATORS: 2048 JSON_OBJECT_AS_ARRAY: 1 JSON_BIGINT_AS_STRING: 2 JSON_ERROR_NONE: 0 JSON_ERROR_DEPTH: 1 JSON_ERROR_STATE_MISMATCH: 2 JSON_ERROR_CTRL_CHAR: 3 JSON_ERROR_SYNTAX: 4 JSON_ERROR_UTF8: 5 JSON_ERROR_RECURSION: 6 JSON_ERROR_INF_OR_NAN: 7 JSON_ERROR_UNSUPPORTED_TYPE: 8 JSON_ERROR_INVALID_PROPERTY_NAME: 9 JSON_ERROR_UTF16: 10
Если вы хотите распарсить JS объект из HTML страницы или файла, то скорее всего json_decode вернет ошибку т.к. в коде будут управляющие символы или BOM. Удалить их можно следующим образом:
$json = ''; // Удаление управляющих символов for ($i = 0; $i // Удаление символа Delete $json = str_replace(chr(127), '', $json); // Удаление BOM if (0 === strpos(bin2hex($json), 'efbbbf')) < $json = substr($json, 3); >$res = json_decode($json, true); print_r($res);
HTTP-запросы в формате JSON
Некоторые сервисы требуют чтобы запросы к ним осуществлялись в формате JSON, такой запрос можно сформировать в CURL:
$data = array( 'name' => 'snipp.ru' 'text' => 'Отправка сообщения', ); $ch = curl_init('https://example.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); $res = curl_exec($ch); curl_close($ch);
А также могут обратится к вашим скриптам в таком формате, чтение JSON запроса.
$data = file_get_contents('php://input'); $data = json_decode($data, true);