Fast Color JSON Marshaller + Pretty Printer for Golang

Overview

ColorJSON: The Fast Color JSON Marshaller for Go

ColorJSON Output What is this?

This package is based heavily on hokaccha/go-prettyjson but has some noticible differences:

  • Over twice as fast (recursive descent serialization uses buffer instead of string concatenation)
    BenchmarkColorJSONMarshall-4     500000      2498 ns/op
    BenchmarkPrettyJSON-4            200000      6145 ns/op
    
  • more customizable (ability to have zero indent, print raw json strings, etc...)
  • better defaults (less bold colors)

ColorJSON was built in order to produce fast beautiful colorized JSON output for Saw.

Installation

go get -u github.com/TylerBrock/colorjson

Usage

Setup

import "github.com/TylerBrock/colorjson"

str := `{
  "str": "foo",
  "num": 100,
  "bool": false,
  "null": null,
  "array": ["foo", "bar", "baz"],
  "obj": { "a": 1, "b": 2 }
}`

// Create an intersting JSON object to marshal in a pretty format
var obj map[string]interface{}
json.Unmarshal([]byte(str), &obj)

Vanilla Usage

s, _ := colorjson.Marshal(obj)
fmt.Println(string(s))

Customization (Custom Indent)

f := colorjson.NewFormatter()
f.Indent = 2

s, _ := f.Marshal(v)
fmt.Println(string(s))
Issues
  • json.Number not handled

    json.Number not handled

    The encoding/json library allows you to use the Decoder type to parse JSON and preserve the formatting of numbers using the UseNumber method. When doing this, colorjson fails to render the numbers in the output.

    With the following code:

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"strings"
    	"github.com/TylerBrock/colorjson"
    )
    
    func main() {
    	str := `{
      "str": "foo",
      "num": 100.0,
      "bool": false,
      "null": null,
      "array": ["foo", "bar", "baz"],
      "obj": { "a": 1, "b": 2 }
    }`
    
    	d := json.NewDecoder(strings.NewReader(str))
    	d.UseNumber()
    	var obj interface{}
    	_ = d.Decode(&obj)
    
    
    	f := colorjson.NewFormatter()
    	f.Indent = 2
    
    	s, _ := colorjson.Marshal(obj)
    	fmt.Println(string(s))
    
    }
    

    The output is shown below (note the absence of any numeric values

    { "array": [ "foo", "bar", "baz" ], "bool": false, "null": null, "num": , "obj": { "a": , "b":  }, "str": "foo" } 
    

    The expected output is below (note that num is rendered as 100.0 rather than 100 as it would have been output without the UseNumber call)

    { "array": [ "foo", "bar", "baz" ], "bool": false, "null": null, "num": 100.0, "obj": { "a": 1, "b": 2 }, "str": "foo" }
    
    opened by stuartleeks 2
  • Should this project still be working?

    Should this project still be working?

    I've been trying to get this library working, but no matter what I always get an empty array ([]) as the result, even though json.Marshal works just fine.

    Usage between colorjson.Marshal and json.Marshal is identical, and there are no errors, so I'm not sure what's up.

    opened by Dids 1
  • Add option to disable HTML escaping in strings

    Add option to disable HTML escaping in strings

    Pretty printing strings with HTML unsafe characters (e.g <) can be quite "unpretty" with the default HTML escaping. This PR adds option to control this.

    The RawStrings option can achieve similar effect, but with this option the output is both pretty and still valid JSON.

    I kept the original code path using json.Marshal as before, so the performance with default options should not be affected except for the bool check.

    opened by noise64 0
  • marshalValue silently fails for unsupported values

    marshalValue silently fails for unsupported values

    marshalValue doesn't handle the wide range of values supported by encoding/json (such as any value implementing json.Marshaler) but silently fails (no output) instead of reporting an error indicating an unsupported data type.

    Example: https://play.golang.org/p/dmF0aGDl0J5

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"log"
    
    	"github.com/TylerBrock/colorjson"
    )
    
    func main() {
    	raw := json.RawMessage(`{
      "str": "foo",
      "num": 100,
      "bool": false,
      "null": null,
      "array": ["foo", "bar", "baz"],
      "obj": { "a": 1, "b": 2 }
    }`)
    
    	f := colorjson.NewFormatter()
    	f.Indent = 2
    
    	b, err := f.Marshal(raw)
    	if err != nil {
    		log.Fatal(err)
    	}
    	if len(b) == 0 {
    		log.Fatal("no output")
    	}
    	fmt.Println(string(b))
    }
    
    opened by dolmen 3
  • Added support for ints, uints and float32

    Added support for ints, uints and float32

    I added support for various int and uint types, as well as float32.

    I understand that your library was targeting unmarshalled JSON structs, so this might not be in scope. I am using colorjson to pretty-print my structs for debugging purposes and noticed that since these types aren't implemented, they return as an empty string in the output.

    Also, unsure if there's a better way to implement this; Golang doesn't seem to like grouping int/uint types together and then type casting, so I have to make a case for each. The other option would of course be to use reflect but it's quite a bit slower.

    opened by bt 6
Owner
Tyler Brock
CTO at @Hustle
Tyler Brock
JSON Spanner - A Go package that provides a fast and simple way to filter or transform a json document

JSON SPANNER JSON Spanner is a Go package that provides a fast and simple way to

null 3 Jun 30, 2022
Fast JSON serializer for golang.

easyjson Package easyjson provides a fast and easy way to marshal/unmarshal Go structs to/from JSON without the use of reflection. In performance test

Free and open source software developed at Mail.Ru 3.8k Jun 22, 2022
Kazaam was created with the goal of supporting easy and fast transformations of JSON data with Golang

kazaam Description Kazaam was created with the goal of supporting easy and fast transformations of JSON data with Golang. This functionality provides

Qntfy 205 Sep 17, 2021
Get JSON values quickly - JSON parser for Go

get json values quickly GJSON is a Go package that provides a fast and simple way to get values from a json document. It has features such as one line

Josh Baker 10.5k Jun 30, 2022
JSON diff library for Go based on RFC6902 (JSON Patch)

jsondiff jsondiff is a Go package for computing the diff between two JSON documents as a series of RFC6902 (JSON Patch) operations, which is particula

William Poussier 172 Jun 23, 2022
Package json implements encoding and decoding of JSON as defined in RFC 7159

Package json implements encoding and decoding of JSON as defined in RFC 7159. The mapping between JSON and Go values is described in the documentation for the Marshal and Unmarshal functions

High Performance, Kubernetes Native Object Storage 3 May 10, 2022
Json-go - CLI to convert JSON to go and vice versa

Json To Go Struct CLI Install Go version 1.17 go install github.com/samit22/js

Samit Ghimire 5 Mar 3, 2022
Fast JSON parser and validator for Go. No custom structs, no code generation, no reflection

fastjson - fast JSON parser and validator for Go Features Fast. As usual, up to 15x faster than the standard encoding/json. See benchmarks. Parses arb

Aliaksandr Valialkin 1.6k Jun 21, 2022
Fast and flexible JSON encoder for Go

Jettison Jettison is a fast and flexible JSON encoder for the Go programming language, inspired by bet365/jingo, with a richer features set, aiming at

William Poussier 128 Jun 1, 2022
A fast json parser for go

rjson rjson is a json parser that relies on Ragel-generated state machines for most parsing. rjson's api is minimal and focussed on efficient parsing.

WillAbides 47 Jun 15, 2022
A blazingly fast JSON serializing & deserializing library

Sonic A blazingly fast JSON serializing & deserializing library, accelerated by JIT(just-in-time compiling) and SIMD(single-instruction-multi-data). B

Bytedance Inc. 3k Jun 24, 2022
Fast json for go. Lightweight fork of jsoniter.

jx Fast json for go. Lightweight fork of jsoniter. Features Reduced scope (no reflection or encoding/json adapter) Fuzzing, improved test coverage Dra

ogen 61 Jun 25, 2022
Abstract JSON for golang with JSONPath support

Abstract JSON Abstract JSON is a small golang package provides a parser for JSON with support of JSONPath, in case when you are not sure in its struct

Stepan Pyzhov 119 Jun 24, 2022
JSON query in Golang

gojq JSON query in Golang. Install go get -u github.com/elgs/gojq This library serves three purposes: makes parsing JSON configuration file much easie

Qian Chen 182 Apr 27, 2022
Automatically generate Go (golang) struct definitions from example JSON

gojson gojson generates go struct definitions from json or yaml documents. Example $ curl -s https://api.github.com/repos/chimeracoder/gojson | gojson

Aditya Mukerjee 2.5k Jun 23, 2022
Arbitrary transformations of JSON in Golang

kazaam Description Kazaam was created with the goal of supporting easy and fast transformations of JSON data with Golang. This functionality provides

Qntfy 230 Jun 17, 2022
Parsing JSON is a hassle in golang

GoJSON Parsing JSON is a hassle in golang. This package will allow you to parse and search elements in a json without structs. Install gojson go get g

swaraj18 25 Nov 12, 2021
Fastest JSON interperter for golang

Welcome To JIN "Your wish is my command" Fast and Easy Way to Deal With JSON Jin is a comprehensive JSON manipulation tool bundle. All functions teste

eco 58 May 28, 2022
Golang port of simdjson: parsing gigabytes of JSON per second

This is a Golang port of simdjson, a high performance JSON parser developed by Daniel Lemire and Geoff Langdale. It makes extensive use of SIMD instructions to achieve parsing performance of gigabytes of JSON per second.

High Performance, Kubernetes Native Object Storage 1.3k Jun 25, 2022