tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
13.95k stars 841 forks source link

Human-friendly output #296

Closed garymoon closed 1 year ago

garymoon commented 1 year ago

I was looking for some kind of more human-friendly representation of JSON. @pretty works perfectly, but all the braces, brackets, commas, quotes etc aren't needed.

To my great surprise, apparently YAML is a superset of JSON, and it can often be parsed as-is (with some caveats depending on the parser). This is certainly of no use for inclusion into gjson, but I thought I'd put it here in case someone else was looking for a similar hackjob.

Thanks for gjson Mr. Baker! :blue_heart: I'll close this to keep noise low.

https://go.dev/play/p/wMmwivHWW_U

P.S. I'm using yaml.v2 to preserve order. It can be done with v3 just the same by switching out the yaml.MapSlice for an interface{}. RedHat please :pray:

package main

import (
    "log"

    yaml "gopkg.in/yaml.v2"
)

func jsonToHuman(json string) (string, error) {
    var unmarshaled interface{}

    err := yaml.Unmarshal([]byte(json), &unmarshaled)
    if err != nil {
        return "", err
    }

    marshaled, err := yaml.Marshal(&unmarshaled)
    if err != nil {
        return "", err
    }

    return string(marshaled), nil
}

var json = `{
  "ip": "1.1.1.1",
  "hostname": "one.one.one.one",
  "anycast": true,
  "city": "Los Angeles",
  "region": "California",
  "country": "US",
  "loc": "34.0522,-118.2437",
  "org": "AS13335 Cloudflare, Inc.",
  "postal": "90076",
  "timezone": "America/Los_Angeles",
  "privacy": {
    "vpn": false,
    "proxy": false,
    "tor": false,
    "relay": false,
    "hosting": true,
    "service": ""
  }
}`

func main() {
    humanReadable, err := jsonToHuman(json)
    if err != nil {
        log.Fatal("Couldn't parse json: ", err)
    }
    log.Print("\n", humanReadable)
}