Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool
Building Browser Bookmarklets for JSON Formatting
Working with APIs, logs, or configuration files often means encountering raw, unformatted JSON data. While many online tools and browser extensions exist for formatting JSON, building a simple bookmarklet offers a quick, tool-independent way to clean up that data directly in your browser window. This article will guide you through creating a basic JSON formatter bookmarklet using plain JavaScript.
What is a Bookmarklet?
A bookmarklet is a bookmark stored in a web browser that contains JavaScript code instead of a URL. When you click a bookmarklet, the JavaScript code is executed on the currently open page. This allows you to add custom functionality or modify the page's content dynamically.
The Core JavaScript: Parsing and Stringifying
The magic behind formatting JSON in JavaScript lies in two built-in methods:
JSON.parse(text)
: Takes a JSON string and transforms it into a JavaScript object or array.JSON.stringify(object, replacer, space)
: Takes a JavaScript object or array and converts it back into a JSON string.
The key for formatting is the third argument of JSON.stringify
: space
. This argument specifies the number of spaces or the string to use for indentation. Using null
for the replacer
and 2
for the space
is a common way to get human-readable, indented output.
Basic Formatting Example:
const rawJsonString = '{"name":"Alice","age":30,"city":"New York"}'; try { // Parse the raw JSON string into a JavaScript object const jsonObject = JSON.parse(rawJsonString); // Stringify the object back into a formatted JSON string const formattedJsonString = JSON.stringify(jsonObject, null, 2); console.log(formattedJsonString); /* Output: { "name": "Alice", "age": 30, "city": "New York" } */ } catch (error) { console.error("Failed to parse JSON:", error); }
This simple pattern of parse then stringify is the foundation of our bookmarklet.
Crafting the Bookmarklet URL
A bookmarklet URL starts with the javascript:
pseudo-protocol, followed by the JavaScript code you want to execute.
All the code must be on a single line and properly encoded for use in a URL. However, browsers are quite forgiving, and often basic minification and wrapping in an Immediately Invoked Function Expression (IIFE) is sufficient.
Bookmarklet Structure:
javascript:(function() { /* Your JavaScript code here */ })();
Wrapping the code in an IIFE (function(){...})()
is a good practice to prevent variables from polluting the global scope of the page you're running it on. The javascript:
prefix tells the browser to execute the code that follows instead of navigating to a new page.
Building the Basic Formatter Bookmarklet
For a straightforward bookmarklet, let's assume you are on a page where the primary content is the raw JSON text (e.g., viewing a JSON file directly in the browser, or an API response displayed as plain text). The bookmarklet will grab the text content of the page body, attempt to parse and format it, and then replace the entire page's content with the formatted result.
Step 1: Get the Raw JSON
We can get the text content of the entire page body using document.body.textContent
.
const rawJsonString = document.body.textContent;
Step 2: Parse and Format (with Error Handling)
It's crucial to include error handling in case the page content is not valid JSON. A try...catch
block is perfect for this.
let formattedJsonString; try { const jsonObject = JSON.parse(rawJsonString); formattedJsonString = JSON.stringify(jsonObject, null, 2); } catch (error) { formattedJsonString = "Error: Could not parse JSON.\nDetails: " + error.message; console.error("JSON Parsing Error:", error); // Log error to console as well }
Step 3: Display the Result
Replace the current page content with the formatted string or the error message. To make it look like formatted code, we can replace the entire HTML content with a simple structure containing a <pre>
tag.
document.documentElement.innerHTML = ''; // Clear existing content const pre = document.createElement('pre'); pre.textContent = formattedJsonString; document.body.appendChild(pre); document.body.style.margin = '20px'; // Add some margin document.body.style.whiteSpace = 'pre-wrap'; // Ensure wrapping for long lines
Step 4: Combine and Minify
Now, let's put all the pieces inside the IIFE and add the javascript:
prefix. We'll remove comments and line breaks to get a single line of code.
Raw JavaScript Code:
(function() { const rawJsonString = document.body.textContent.trim(); let formattedJsonString; if (!rawJsonString) { formattedJsonString = "No text content found on the page."; } else { try { const jsonObject = JSON.parse(rawJsonString); formattedJsonString = JSON.stringify(jsonObject, null, 2); } catch (error) { formattedJsonString = "Error: Could not parse JSON.\nDetails: " + error.message; console.error("JSON Parsing Error:", error); } } document.documentElement.innerHTML = '<head><title>Formatted JSON</title></head><body><pre></pre></body>'; const pre = document.querySelector('pre'); pre.textContent = formattedJsonString; document.body.style.margin = '20px'; document.body.style.whiteSpace = 'pre-wrap'; document.body.style.wordWrap = 'break-word'; // Added for better wrapping })();
Minifying this (removing extra whitespace, comments) and putting it after javascript:
gives us the bookmarklet URL.
The Bookmarklet URL (Example, actual code minified):
javascript:(function(){document.documentElement.innerHTML='';var pre=document.createElement('pre');pre.style.cssText='word-wrap: break-word; white-space: pre-wrap;';var rawJson=document.body.textContent.trim();var formattedJson='No text content found on the page.';try{if(rawJson){formattedJson=JSON.stringify(JSON.parse(rawJson),null,2);}}catch(e){formattedJson='Error: Could not parse JSON.\\nDetails: '+e.message;console.error('JSON Parsing Error:',e);}pre.textContent=formattedJson;document.body.appendChild(pre);document.body.style.margin='20px';})();
Note: The bookmarklet code shown above in the <code>
block is a minified version of the raw JavaScript. You would use this single line, starting with javascript:
, as the URL for your bookmarklet.
How to Install and Use
- Create a new bookmark: In your browser's bookmark manager or by dragging the current page's icon to the bookmarks bar.
- Edit the bookmark: Right-click the new bookmark and select "Edit" (or equivalent).
- Name it: Give it a descriptive name like "Format JSON".
- Paste the code as the URL: Copy the full bookmarklet code (starting with
javascript:
) from the previous step and paste it into the URL field, replacing the existing URL. - Save: Save the bookmark.
To use it, navigate to a page containing raw JSON text. Then, simply click the "Format JSON" bookmarklet from your bookmarks bar or menu. The page content should be replaced with the formatted JSON.
Variations and Considerations
- Formatting Options: You can easily change the indentation (e.g.,
JSON.stringify(jsonObject, null, 4)
for 4 spaces, orJSON.stringify(jsonObject, null, '\\t')
for tabs). - Targeting Specific Elements: Instead of using
document.body.textContent
, you could modify the script to look for JSON within a specific HTML element (e.g., an element with a certain ID or class), though this makes the bookmarklet less generic. - Copy to Clipboard: Instead of replacing the page content, the bookmarklet could copy the formatted JSON to the user's clipboard using the Clipboard API(
navigator.clipboard.writeText(...)
), which might be more convenient in many cases. - Handling Large JSON: For very large JSON strings, parsing and re-stringifying can be slow or even crash the tab. Bookmarklets are best suited for moderately sized data.
- Page Structure: This basic bookmarklet works best on pages that consist almost entirely of the raw JSON text. Running it on complex web pages with lots of HTML and other content might yield unpredictable results as
document.body.textContent
will grab everything.
Conclusion
Building a JSON formatting bookmarklet is a great way to understand how bookmarklets work and leverage simple browser APIs like JSON.parse
and JSON.stringify
. It provides a handy, portable tool that you can use across different websites without needing to install extensions or paste sensitive data into third-party online formatters. While basic, the core logic can be extended to handle different scenarios and add more features.
Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool