Parse JSON: What is JSON parsing and how does it work? | Indepth (2024)

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: What is JSON parsing and how does it work? | Indepth (1)

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.

Parse JSON: What is JSON parsing and how does it work? | Indepth (2)

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 JSONconst parsedJson = JSON.parse(jsonString)console.log(parsedJson.name)// output:// Joe// change something in the dataparsedJson.winner = true// serialize: stringify JSON into textconst 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 jsonjsonString = '{"name":"Joe","age":42,"scores":[31.4,29.9,35.7],"winner":false}'# deserialize: parse text into JSONparsedJson = json.loads(jsonString)print(parsedJson['name'])# output:# 'Joe'# change something in the dataparsedJson['winner'] = True# serialize: stringify JSON into textstringifiedJson = 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 ObjectMapperObjectMapper 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 dataUser user = mapper.readValue(jsonString, User.class);System.out.println(user.getName()); // output: Joe// change something in the datauser.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 exampleconst list = partialJsonParse('[4,1,2]')const add = (a, b) => a + bconsole.log(list.reduce(add))// output: 7const 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()}
Parse JSON: What is JSON parsing and how does it work? | Indepth (2024)
Top Articles
Deriv Trader | Options Trading Platform | Deriv
Student Worksheet: Graphing Spectra
Exclusive: Baby Alien Fan Bus Leaked - Get the Inside Scoop! - Nick Lachey
123Movies Encanto
Usborne Links
Poe Pohx Profile
Evita Role Wsj Crossword Clue
Rainfall Map Oklahoma
Lqse-2Hdc-D
Helloid Worthington Login
Love In The Air Ep 9 Eng Sub Dailymotion
Petco Vet Clinic Appointment
Full Standard Operating Guideline Manual | Springfield, MO
Poe Str Stacking
Why do rebates take so long to process?
Sussyclassroom
Gas Buddy Prices Near Me Zip Code
12 Facts About John J. McCloy: The 20th Century’s Most Powerful American?
Ou Class Nav
Yale College Confidential 2027
John Philip Sousa Foundation
This Is How We Roll (Remix) - Florida Georgia Line, Jason Derulo, Luke Bryan - NhacCuaTui
Taylored Services Hardeeville Sc
Page 2383 – Christianity Today
Vlacs Maestro Login
DIY Building Plans for a Picnic Table
Bfri Forum
Loopnet Properties For Sale
Dubois County Barter Page
South Florida residents must earn more than $100,000 to avoid being 'rent burdened'
Lowell Car Accident Lawyer Kiley Law Group
#scandalous stars | astrognossienne
Bridger Park Community Garden
Cvb Location Code Lookup
Agematch Com Member Login
AsROck Q1900B ITX und Ramverträglichkeit
Viewfinder Mangabuddy
KM to M (Kilometer to Meter) Converter, 1 km is 1000 m
Henry County Illuminate
Main Street Station Coshocton Menu
Tillman Funeral Home Tallahassee
Second Chance Apartments, 2nd Chance Apartments Locators for Bad Credit
Gateway Bible Passage Lookup
Trivago Sf
COVID-19/Coronavirus Assistance Programs | FindHelp.org
Craigslist Antique
From Grindr to Scruff: The best dating apps for gay, bi, and queer men in 2024
Greatpeople.me Login Schedule
Underground Weather Tropical
Grand Park Baseball Tournaments
Bama Rush Is Back! Here Are the 15 Most Outrageous Sorority Houses on the Row
Wrentham Outlets Hours Sunday
Latest Posts
Article information

Author: Jeremiah Abshire

Last Updated:

Views: 5499

Rating: 4.3 / 5 (54 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Jeremiah Abshire

Birthday: 1993-09-14

Address: Apt. 425 92748 Jannie Centers, Port Nikitaville, VT 82110

Phone: +8096210939894

Job: Lead Healthcare Manager

Hobby: Watching movies, Watching movies, Knapping, LARPing, Coffee roasting, Lacemaking, Gaming

Introduction: My name is Jeremiah Abshire, I am a outstanding, kind, clever, hilarious, curious, hilarious, outstanding person who loves writing and wants to share my knowledge and understanding with you.