json

Pretty print JSON in python

Snippet
import json

Use json.dumps and

...
 
def import_json_files(directory):
    json_files = []
    try:
        for filename in os.listdir(directory):
            if filename.endswith(".json"):
                print(f"Processing {filename}")
                if os.path.getsize(os.path.join(directory, filename)) > 0:
                    with open(os.path.join(directory, filename), 'r') as file:
                        data = json.load(file)
                        #
                        #
                        # Convert the JSON to a string, adjusting the indentation on output
                        #
                        #
                        json_str = json.dumps(data[0], indent=4)
                        print(json_str)
                        #
                        #
                        #
                        json_files.append(data)
                else:
                    print(f" ** empty file!")
        return json_files
    except FileNotFoundError:
        print(f"Directory {directory} not found.")
        return None
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        return None
 
...

Pretty print a json file

Snippet

JSON comes over the wire with minimal spaces, making human parsing of the object difficult. The json lib provides an easy way to reformat it into an indented format.

Remember to use #!/usr/bin/env so that any rbenv or rvm specific versions of ruby will be used.

Dump this into a file, say, format-json.rb, and use with:

format-json.rb my-squashed.json > nicely-readable.json

Usage:

#!/usr/bin/env ruby
 
require 'json'
 
exit if ARGV[0].nil?
 
puts JSON.pretty_generate(JSON.parse(File.read(ARGV[0])))

Parse JSON from server in javascript

Snippet

When a server response (say, from an ajax call) returns JSON formatted code, eval to bring the results into the script's space. Don't use with any returned JSON object that you don't really really really trust.

/*
 server returns 
 {"a":1,"b":2,"c":3,"d":4,"e":5}
 */
 
// NEVER DO THIS
var obj = eval('(' + jsontext + ')');
alert(obj.a);
// will receive "1" in alert (no quotes)
 
// DO THIS
JSON.parse( json.data );