go-simplejson
a Go package to interact with arbitrary JSON
Importing
import github.com/bitly/go-simplejson
Documentation
Visit the docs on Go package discovery & docs
a Go package to interact with arbitrary JSON
import github.com/bitly/go-simplejson
Visit the docs on Go package discovery & docs
The (only) constructor for *Json is from a []byte
, which is not always ideal. Using an io.Reader
can provide a small speed-up and reduction of memory usage, particularly in the case that the underlying JSON is large.
(My use-case was unmarshaling from an http.Response.Body
containing arbitrary JSON.)
This defers the actual parsing of the text value to the numeric type until you dereference it using the Int(), Int64() or Float64() receiver methods.
This has the benefit that large integers (>= 1e6) are not marshaled in floating point exponent notation, and that very large integers (>= 2^53) do not lose precision when marshaled because they were stored internally as float64s.
I started exploring interface with some tests to see if we can update part of JSON using GetPath()
.. Set()
, which it seems you cannot do. My use case is that I have some path (the word "branch" is used in the code), and I want to update this with some value.
I've added SetBranch
which you'd use like this:
js, err := NewJson([]byte(`{}`))
js.SetBranch([]string{"foo", "bar"}, "baz")
s, _ := js.GetPath("foo", "bar").String()
// s = "baz"! yay
I was tempted to do the API as SetBranch(val interface{}, branch ...string)
but the pay back of getting the ...
seems outweighed by the confusion of swapping key
and value
(relative to the Set
method).
I'd love to avoid having to call Array()
to get the length of an array element. But what I really want to do is iterate over the array length, like:
js.Get("json_node_with_array").Length()
or
len(js.Get("json_node_with_array"))
Alternatively, I'd be happy with a range operation:
for i, arrayElement := range js.Get("json_node_with_array") { arrayElement == js.Get("json_node_with_array").GetIndex(i) }
Which one of those approaches seems right to you?
I think life will be a lot easier if Map/MustMap/Array/MustArray would return *Json instead of interface{}. No type assertion or casting would not be needed. Currently, it's like this:
func (j *Json) Map() (map[string]interface{}, error)
func (j *Json) MustMap(args ...map[string]interface{}) map[string]interface{}
func (j *Json) Array() ([]interface{}, error)
func (j *Json) MustArray(args ...[]interface{}) []interface{}
What I'm hoping is:
func (j *Json) Map() (map[string]*Json, error)
func (j *Json) MustMap(args ...map[string]interface{}) map[string]*Json
func (j *Json) Array() ([]*Json, error)
func (j *Json) MustArray(args ...[]interface{}) []*Json
Best regards, Elgs
Implements interfaces for go-simplejson to play nicely with the standard library's "encoding/json" package. Allows *Json types as struct fields, map values, and slice elements to be marshaled (and unmarshaled).
Also updates README.md which was missing the Bool()
method
i have json like [{"a":1},{"b":2}]
want to append {"c":3} to json array
result is [{"a":1},{"b":2},{"c":3}]
how? thank you very much
i have string
teststring := {"fields_desc": {"cpUin": "44444" }}
js,_ := simplejson.NewJson([]byte(teststring))
my question is how can i convert js to string? i use js.string(), but i get "".
I've created a Virtualbox-backed Vagrant box (hashicorp/precise64
image with 2 CPUs and 2048Mb of memory), installed git (using apt) and go 1.3.3 to the current directory from official tarball (https://storage.googleapis.com/golang/go1.3.3.linux-amd64.tar.gz) and try to build the google_auth_proxy:
vagrant@precise64:~$ GOROOT=go GOPATH=gopath go/bin/go get github.com/bitly/go-simplejson
go build github.com/bitly/go-simplejson: fork/exec go/pkg/tool/linux_amd64/6g: no such file or directory
vagrant@precise64:~$ ls -l go/pkg/tool/linux_amd64/6g
-rwxr-xr-x 1 vagrant vagrant 3461435 Oct 1 01:51 go/pkg/tool/linux_amd64/6g
vagrant@precise64:~$
At the same time I've tried doing the same on AWS and the build went fine.
(Not sure it in any way relates to the topic but I've run into that when I was trying to build google_auth_proxy
, by the way thank you for the great tool)
I cannot get int value with MustInt after I set it. This example illustrate the problem:
func TestSetInt(t *testing.T) {
js, _ := simplejson.NewJson([]byte(`{"x":1}`))
t.Log("before", js.Get("x").MustInt())
js.Set("x", 2)
t.Log("after", js.Get("x").MustInt())
}
output:
before 1
after 0
Hi
I have json data like this:
{ "samekey": "value1", "samekey": "value2", "samekey": "value3" }
How to get the third one? I mean that which built-in function should I use.
Thanks in advance.
Hello.
is there any way to test the value for NULL?
Assume we have a json
{"someid":null}
And I want to test if the value is null, not just empty. For testing it as empty I can do something like require.Empty(simplejsonData.Get("someid"))
Any help is appreciated.
I want to iterate an array, and use the elements of the array as *simplejson.Json. I found no function to get size of array, the only way I found is to calculate len(jsonObj.Array), and I have no way to change jsonObj.MustArray()[i] to *simplejson.Json.
import (
"fmt"
sjson "github.com/bitly/go-simplejson"
)
func main() {
body := `"{"client_id":"abc123","client_ip":"59.37.125.15","client_version":"1"}"`
// body := `{"client_id":"abc123","client_ip":"59.37.125.15","client_version":"1"}`
js, err := sjson.NewJson([]byte(body))
if err != nil {
fmt.Printf("failed to decode json(%s): %v", body, err) // should fail, but it does not!
return
}
fmt.Printf("js: (%v)\n", js)
return
}
When the encoded json field contains &, < or > symbols, they will be encoded in the form of ascii code. I know this is due to the json library and can be avoided by setEscapeHTML. Can you provide a similar function?
Hi, I had added ppc64le(Linux on Power) support on travis-ci in the branch and looks like its been successfully added. I believe it is ready for the final review and merge. The travis ci build logs can be verified from the link below.
https://travis-ci.com/github/ujjwalsh/go-simplejson/builds/188445179 Please have a look.
Regards, ujjwal
kazaam Description Kazaam was created with the goal of supporting easy and fast transformations of JSON data with Golang. This functionality provides
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
JSON SPANNER JSON Spanner is a Go package that provides a fast and simple way to
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
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
Fast JSON encoder/decoder compatible with encoding/json for Go
Json To Go Struct CLI Install Go version 1.17 go install github.com/samit22/js
go-respond A Go package for handling common HTTP JSON responses. Installation go get github.com/nicklaw5/go-respond Usage The goal of go-respond is to
A simple Go package to Query over JSON Data. It provides simple, elegant and fast ODM like API to access, query JSON document Installation Install the
vjson vjson is a Go package that helps to validate JSON objects in a declarative way. Getting Started Installing For installing vjson, use command bel
jsonc jsonc is a Go package that converts the jsonc format to standard json. The jsonc format is like standard json but allows for comments and traili
JSONata in Go Package jsonata is a query and transformation language for JSON. It's a Go port of the JavaScript library JSONata.
simple_json_compare A very rudimentary JSON compare package Sample code package main import ( "fmt" "github.com/CalypsoSys/simple_json_compare" )
JSON-LD ?? Simple JSON-LD in Go This is an experimental package for working with JSON-LD documents in Go. Experimental, Pre-Alpha Quality Please do no
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
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
gjo Small utility to create JSON objects. This was inspired by jpmens/jo. Support OS Mac Linux Windows Requirements Go 1.1.14~ Git Installtion Build $
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
gojson gojson generates go struct definitions from json or yaml documents. Example $ curl -s https://api.github.com/repos/chimeracoder/gojson | gojson