Scripting
How to handle JSON data in a scripting language
Within a programming language, convert a JSON-formatted string to data structure and then back to a string.
See also JSON section of my data formats guide.
JavaScript
No imports needed.
JSON.parse(myString);
JSON.stringify(myObject);
Prettify with indentation.
JSON.stringify(results, null, 4)
In NodeJS on the command-line:
> var package = require('./package.json')
> package.version
"1.0.0"
Ruby
Import a builtin:
require 'json'
JSON.parse my_string
JSON.generate my_object
JSON.pretty_generate my_object
Or on an object. Also needs the import as above to add this method.
my_string.to_json
{:hello => "world"}.to_json
# => "{\"hello\":\"world\"}"
Jekyll
null
Python
- Reading and writing JSON to a file in Python on StackAbuse.
- Reading and writing JSON to a file in Python on Geeks for Geeks.
Import the builtin.
import json
Object handling
Read from and write to object - note the s
in the method name.
my_obj = json.loads(my_string)
my_string = json.dumps(my_obj)
File handling
Read from and write to file - note *no s
in the method names.
with open('file.json') as f_in:
my_obj = json.load(f_in)
with open('file.json', 'w') as f_out:
json.dumps(my_object, f_out)
Pretty print
Be sure to specify wrapping indentation level at 4 spaces to make the output appear more vertical than horizontal.
print(json.dumps(my_obj, indent=4)
Alternatively, use the pprint
built which will also wrap data stuctures for easy reading but does not impose JSON on everything. For example, JSON does not handle datetime object so you’d have to stringify those with str(value)
before you convert to JSON.
import pprint
Using a function:
pprint.pprint(my_object)
# Width is in number of characters.
pprint.pprint(my_object, depth=1, width=60)
Using a class:
pp = pprint.PrettyPrinter(width=60, compact=True)
pp.pprint(my_object)
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(my_object)
Flask
A Python library for websites and APIs. It supports templating using HTML files with Liquid syntax, similar to Jekyll.
Depending how you want certain characters to appear, you might use the safe
filter.