Skip to content
This repository has been archived by the owner on Mar 21, 2024. It is now read-only.

nikolaydubina/multiline-jsonl

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Note 2022-06-11: first check this https://pkg.go.dev/encoding/json#Decoder


This package was build for programmatic access of multiline JSON in Go.
If you need CLI for JSON, I highly recommend jq.

Go Reference Go Report Card

$ go install github.com/nikolaydubina/multiline-jsonl@latest

For example, you want to parse input multiline JSONs

$ echo '{
    "from":"github.com/nikolaydubina/jsonl-graph/graph",
    "to":"bufio"
}

{"from":"my-id-1","to":"my-id-2"}
{"from":"my-id-5","to":"my-id-10", "amount": 123}
{"from":"my-id-5","to":"my-id-10", "amount": {"amount": 123, "currency": "KRW"}}

{
    "id": "my-id",
    "number": 123,
    "nested": {
        "title": "big title",
        "nested-level-2": {
            "subtitle": "some other thing",
            "count": 123
        }
    }
}

' | ./multiline-jsonl

Outputs shortened version

{"from":"github.com/nikolaydubina/jsonl-graph/graph","to":"bufio"}
{"from":"my-id-1","to":"my-id-2"}
{"amount":123,"from":"my-id-5","to":"my-id-10"}
{"amount":{"amount":123,"currency":"KRW"},"from":"my-id-5","to":"my-id-10"}
{"id":"my-id","nested":{"nested-level-2":{"count":123,"subtitle":"some other thing"},"title":"big title"},"number":123}

And with -expand flag

{
    "from": "github.com/nikolaydubina/jsonl-graph/graph",
    "to": "bufio"
}
{
    "from": "my-id-1",
    "to": "my-id-2"
}
{
    "amount": 123,
    "from": "my-id-5",
    "to": "my-id-10"
}
{
    "amount": {
        "amount": 123,
        "currency": "KRW"
    },
    "from": "my-id-5",
    "to": "my-id-10"
}
{
    "id": "my-id",
    "nested": {
        "nested-level-2": {
            "count": 123,
            "subtitle": "some other thing"
        },
        "title": "big title"
    },
    "number": 123
}

Here is example from https://github.com/nikolaydubina/jsonl-graph

func NewGraphFromJSONL(r io.Reader) (Graph, error) {
	g := NewGraph()

	scanner := bufio.NewScanner(r)
	scanner.Split(multilinejsonl.SplitMultilineJSONL)

	for scanner.Scan() {
		decoder := json.NewDecoder(bytes.NewReader(scanner.Bytes()))
		decoder.UseNumber()

		var nodeEdge orNodeDataEdgeData
		if err := decoder.Decode(&nodeEdge); err != nil {
			continue
		}

		node, edge, err := nodeEdge.cast()
		if err != nil {
			return g, fmt.Errorf("can not cast: %w", err)
		}

		switch {
		case node != nil:
			g.AddNode(*node)
		case edge != nil:
			g.AddEdge(*edge)
		}
	}

	return g, scanner.Err()
}

Features

  • No reflection
  • Simple Code
  • CLI
  • 84% coverage

Reference