When you parse JSON, you convert a string containing a JSON document into a structured data object that you can operate on. Learn how this works.
Parse JSON online
Do you just need to parse your JSON online to inspect it? Paste your JSON in the following editor:
What does it mean to parse JSON?
JSON is a data format used to serialize data. Serialization is the process of converting a data object that exists in computer memory into a series of bytes that can be easily persisted or transmitted. Serialized data can be stored on disk, in a database, or sent over between machines, like from a server to a browser. There are various data formats that can be used to serialize data, for example readable formats like JSON, XML, CSV or binary formats like BSON or MS Word .doc files. In this article, we will talk about JSON only. The serialization process has two directions:
- Serialization is the process of turning a data object into a series of bytes. In the context of JSON data, this is often called stringifying JSON.
- Deserializing is the process of turning a series of bytes into a data object. In the context of JSON data, this is often called parsing JSON.
In the following schematic image you see an object in memory of say a web application in your browser. It is an object holding some information about a user. Serialization converts the data into a piece of text that holds all information and the structure of the data: an object with some properties, and the “scores” property is a list holding values. The JSON data holds all information needed to parse the data into an object in memory again.
Why do we need to parse JSON?
For example when you are a web developer, building a web application, you will typically fetch data from a server. For example on a web shop, the application will retrieve a list with products that the user is searching for. The JSON data that you will receive is just “a piece of text” at first. Before you can use the data inside the text, you will have to parse the JSON. After parsing, the data is an object or an array with objects on which you can operate: sort by price or relevance, count the number of results, and map different properties like product name, and description to the user interface.
How do I parse a JSON file?
How to parse a JSON file depends on the programming languages. The JSON standard is well-supported, and all modern programming languages do have either built-in support, or libraries that you can use to parse JSON. In the following sections, a basic example is given on how to convert JSON in different languages: JavaScript, PHP, Python, and Java. You’ll see that it works quite similarly in different languages.
Parsing JSON in JavaScript
JavaScript has a built-in functions JSON.parse and JSON.stringify to work with JSON. The following example demonstrates this, and also shows how to beautify JSON:
const jsonString = '{"name":"Joe","age":42,"scores":[31.4,29.9,35.7],"winner":false}'
// deserialize: parse text into JSON
const parsedJson = JSON.parse(jsonString)
console.log(parsedJson.name)
// output:
// Joe
// change something in the data
parsedJson.winner = true
// serialize: stringify JSON into text
const stringifiedJson = JSON.stringify(parsedJson)
console.log(stringifiedJson)
// output:
// {"name":"Joe","age":42,"scores":[31.4,29.9,35.7],"winner":true}
// stringify formatted JSON with indentation and newlines:
const formattedJson = JSON.stringify(parsedJson, null, 2)
console.log(formattedJson)
// output:
// {
// "name": "Joe",
// "age": 42,
// "scores": [
// 31.4,
// 29.9,
// 35.7
// ],
// "winner": true
// }
Now, JSON is a subset of JavaScript. It originates from JavaScript. So you can literally paste JSON data inside a JavaScript script, and it will be parsed into an object when you run the script. That can be handy when you have some static data in a web application. Since JSON is valid JavaScript, you can also parse JSON using the eval function, which allows dynamically executing JavaScript code. The eval function is generally considered unsafe though: it can be used to inject malicious code into a JavaScript application. So please don’t use eval, or if you do, take careful measures to prevent security risks. This approach is used in the json2.js library by Douglas Crockford (who “discovered” JSON): the library first validates whether there is no malicious code inside the JSON using a regular expression, and after that, it uses eval to parse the JSON.
Parsing JSON in PHP
PHP has built-in functions json_decode
and json_encode
to serialize JSON. You will probably need to do some post processing, since PHP allows either parses the data into objects, or in arrays.
<?php
$jsonString = '{"name":"Joe","age":42,"scores":[31.4,29.9,35.7],"winner":false}';
// deserialize: parse text into a JSON object
// note: use json_decode($text, true) to parse into an array instead of object
$json = json_decode($jsonString, true);
echo $json['name'];
// output:
// Joe
// change something in the data
$json['winner'] = true;
// serialize: stringify JSON into text
$stringified = json_encode($json);
var_dump($stringified);
// output:
// string(63) "{"name":"Joe","age":42,"scores":[31.4,29.9,35.7],"winner":true}"
?>
Parsing JSON in Python
In Python, you can use the json library to work with JSON data. It comes with functions json.loads
and json.dumps
:
import json
jsonString = '{"name":"Joe","age":42,"scores":[31.4,29.9,35.7],"winner":false}'
# deserialize: parse text into JSON
parsedJson = json.loads(jsonString)
print(parsedJson['name'])
# output:
# 'Joe'
# change something in the data
parsedJson['winner'] = True
# serialize: stringify JSON into text
stringifiedJson = json.dumps(parsedJson)
print(stringifiedJson)
# output:
# '{"name": "Joe", "age": 42, "scores": [31.4, 29.9, 35.7], "winner": true}'
Parsing JSON in Java
In Java, there are various libraries available to work with JSON. A popular one is Jackson. Since Java is a strictly typed language, you normally need a data class on which you map your data. We will not write out an in-depth example but here is the gist of it:
// create a jackson ObjectMapper
ObjectMapper mapper = new ObjectMapper();
String jsonString =
"{\"name\":\"Joe\",\"age\":42,\"scores\":[31.4,29.9,35.7],\"winner\":false}";
// deserialize: parse text into JSON
// here we assume we have a User class matching the structure of the data
User user = mapper.readValue(jsonString, User.class);
System.out.println(user.getName()); // output: Joe
// change something in the data
user.setWinner(true);
String stringified = mapper.writeValueAsString(user);
System.out.println(stringified);
// output:
// "{\"name\":\"Joe\",\"age\":42,\"scores\":[31.4,29.9,35.7],\"winner\":true}";
How to use JSON parsing in practice?
In practice, you will often fetch data from a server, from disk, or from a database, and directly afterward parse it. This is often done in one go, by ready-made libraries. For example in plain JavaScript, you can use fetch
:
const response = await fetch(url)
const json = await response.json()
Or you can use a library like Axios, in combination with TypeScript:
import axios from 'axios'
interface User {
name: number
age: string
scores: number[]
winner: boolean
}
interface GetUsersResponse {
data: User
}
const { data } = await axios.get<GetUsersResponse>(url)
In short, most likely, the library that you use to fetch data will handle the parsing for you.
Is it difficult to parse JSON?
No. The JSON data format is very simple, which makes it quite straightforward to implement a parser for it. This is probably one of the reasons that JSON has become so popular: it’s easy to add support for it in any programming language. And also: it is a human-readable text format which makes it easy to have a look at the data without need to parse it. To parse data, you have to iterate over all bytes in the data one by one. When you encounter a [
character, you know it’s the start of an array. Then, if you encounter a digit, you collect all consecutive digits into a number, until you hit a comma or the end of the array ]
. If you want to learn how to write a full JSON parser yourself, you can read the following in-depth tutorial: https://lihautan.com/json-parser-with-javascript. To give you an idea of what it is involved, here is the JavaScript code of a function which can parse JSON arrays and integer numbers:
// usage example
const list = partialJsonParse('[4,1,2]')
const add = (a, b) => a + b
console.log(list.reduce(add))
// output: 7
const nested = partialJsonParse('[[12,52],[33,790]]')
console.log(nested[1][0])
// output: 33
/**
* This partial JSON parser can parse integer numbers and arrays.
* It misses proper error handling, parsing of objects,
* floating point numbers, strings, booleans, null, and white spaces.
* @param {string} str
* @returns {Array | number}
*/
function partialJsonParse(str) {
let i = 0
function parseValue() {
return parseArray() ?? parseInteger()
}
function parseArray() {
if (str[i] === '[') {
i++
const arr = []
let first = true
while (i < str.length && str[i] !== ']') {
if (first) {
first = false
} else {
skipComma()
}
arr.push(parseValue())
}
if (str[i] === ']') {
i++
}
return arr
}
}
function parseInteger() {
let start = i
while (i < str.length && isDigit(str[i])) {
i++
}
return i > start ? parseInt(str.substring(start, i)) : undefined
}
function skipComma() {
if (str[i] === ',') {
i++
}
}
function isDigit(char) {
return char >= '0' && char <= '9'
}
return parseValue()
}