You can pretty print a JSON file or JSON data in various programming languages using built-in libraries or modules. Here are examples in Python, JavaScript, and Ruby:
Python Example (Using the json
Module):
Python provides the json
module for working with JSON data. You can use the json.dumps()
method with the indent
parameter to pretty print JSON data:
python
import json
# Your JSON data
json_data = {
"name": "John",
"age": 30,
"city": "New York"
}
# Pretty print the JSON data
pretty_json = json.dumps(json_data, indent=4)
print(pretty_json)
In this Python example, we import the json
module, create a JSON object, and then use json.dumps()
with indent=4
to produce a nicely formatted JSON string.
JavaScript Example (Using JSON.stringify()
):
In JavaScript, you can use the JSON.stringify()
method with the replacer
and space
parameters to pretty print JSON data:
javascript
// Your JSON data
const json_data = {
name: "John",
age: 30,
city: "New York"
};
// Pretty print the JSON data
const pretty_json = JSON.stringify(json_data, null, 4);
console.log(pretty_json);
In this JavaScript example, we use JSON.stringify()
with null
as the replacer
and 4
as the space
parameter to achieve pretty printing.
Ruby Example (Using the JSON
Module):
In Ruby, you can use the JSON.pretty_generate()
method from the json
module to pretty print JSON data:
ruby
require 'json'
# Your JSON data
json_data = {
"name" => "John",
"age" => 30,
"city" => "New York"
}
# Pretty print the JSON data
pretty_json = JSON.pretty_generate(json_data)
puts pretty_json
In this Ruby example, we require the json
module, create a JSON object, and then use JSON.pretty_generate()
to generate a nicely formatted JSON string.
These examples demonstrate how to pretty print JSON data in Python, JavaScript, and Ruby. The key is to use the appropriate method provided by the respective language's JSON library/module and specify the desired indentation for formatting.
Comments
Post a Comment