Skip to main content
blog title image

2 minute read - Web Testing

Pretty Printing JSON

Feb 4, 2019

Quick tips for pretty printing JSON in the Browser.

All examples in this post use the swapi.dev API

Where do you find JSON?

In the network tab, and from the source, and from proxies, I will very often be observing network traffic, and I’ll want to interrogate the message to view it more easily.

So I copy and paste it from the network tab.

showing json in the network tab

If it is in the network tab, I could use the message preview to format it.

I could also use an online tool to format it and view it:

Or I could use the browser console itself.

Paste the JSON into the console

Pasting the Json into the console will show an interactive view where I can expand and contract the outline and view the JSON.

showing json in the console

Pretty Print it using JavaScript

JavaScript has a built in JSON class and I can use the stringify method to pretty print an object as JSON to the console.

So I first create an object from the JSON:

bob={"name":"Luke Skywalker"}

Then I can pretty print the JSON (4 is the indentation level):

JSON.stringify(bob, null, 4)

e.g

"{
    "name": "Luke Skywalker",
    "height": "172",
    "mass": "77",
    "hair_color": "blond",
    "skin_color": "fair",
    "eye_color": "blue",
    "birth_year": "19BBY",
    "gender": "male",
    "homeworld": "https://swapi.dev/api/planets/1/",
    "films": [
        "https://swapi.dev/api/films/2/",
        "https://swapi.dev/api/films/6/",
        "https://swapi.dev/api/films/3/",
        "https://swapi.dev/api/films/1/",
        "https://swapi.dev/api/films/7/"
    ],
    "species": [
        "https://swapi.dev/api/species/1/"
    ],
    "vehicles": [
        "https://swapi.dev/api/vehicles/14/",
        "https://swapi.dev/api/vehicles/30/"
    ],
    "starships": [
        "https://swapi.dev/api/starships/12/",
        "https://swapi.dev/api/starships/22/"
    ],
    "created": "2014-12-09T13:50:51.644000Z",
    "edited": "2014-12-20T21:17:56.891000Z",
    "url": "https://swapi.dev/api/people/1/"
}"

how to use JSON stringify

Free Video Showing How to Pretty Print JSON


If you found this useful then you might be interested in my Online Technical Web Testing 101 course.