Pretty print JSON

I have a bunch of JSON objects that I’d like to print to the screen.
I’d like to sort the keys to make them easier to read.
This python code does what I want:

#!/usr/bin/env python3
import json

def reorder(s):
    o = json.loads(s)
    return json.dumps(o, sort_keys=True)

input1 = '{"b": 2, "A":1, "c": {"d": 3}}'
input2 = '{"c": {"d": 3}, "b": 2, "A":1}'
print(input1)
print(input2)
print()
print(reorder(input1))
print(reorder(input2))

Outputs:

{"b": 2, "A":1, "c": {"d": 3}}
{"c": {"d": 3}, "b": 2, "A":1}

{"A": 1, "b": 2, "c": {"d": 3}}
{"A": 1, "b": 2, "c": {"d": 3}}

I tried using json.Unmarshal and json.Marshal but it filters out lowercase keys.
It also leaves no spaces in the output, which is a little hard to read.

I don’t know the format of the messages ahead of time.
I only know that they will be JSON objects.

Anyone have a good way of doing this?

Can you use jq ?

Thanks.
jq is a good idea. I could use that, but would prefer a pure Go solution, without dependencies if possible.

Thanks.
Lots of good info there, but most of the answers print the json on multiple lines. I need it all to be on a single line.

I had a mistake in the original question.
json.Unmarshal and json.Marshal do not filter out lowercase keys.
It puts lowercase stuff at the end so I didn’t see it in the output.

So this code does the alphabetical ordering right.

package main

import (
	"encoding/json"
	"fmt"
)

func reorder(obj string) string {
	var o map[string]interface{}
	json.Unmarshal([]byte(obj), &o)
	r, _ := json.Marshal(o)
	return string(r)
}

func main() {
	input1 := `{"b": 2, "A":1, "c": {"d": 3}}`
	input2 := `{"c": {"d": 3}, "b": 2, "A":1}`
	fmt.Println(input1)
	fmt.Println(input2)
	fmt.Println()
	fmt.Println(reorder(input1))
	fmt.Println(reorder(input2))
}

Output:

{"b": 2, "A":1, "c": {"d": 3}}
{"c": {"d": 3}, "b": 2, "A":1}

{"A":1,"b":2,"c":{"d":3}}
{"A":1,"b":2,"c":{"d":3}}

It would just be much more readable if there was a space after each colon and comma.

To pretty print your JSON instead of Marshal function you can simply use MarshalIndent. About reordering, yeah, you can imagine a function to do this but keep in mind that JSON is a format for data exchange and the order of elements is not guaranteed and should not mater.

The JSON Data Interchange Standard definition at json.org specifies that “An object is an unordered [emphasis mine] set of name/value pairs”, whereas an array is an “ordered collection of values”. In other words, by definition the order of the key/value pairs within JSON objects simply does not, and should not, matter .

Ordering Elements within JSON Objects – FileMakerHacks.