Giter Club home page Giter Club logo

jason's Introduction

Jason is an easy-to-use JSON library for Go.

Build Status Godoc license

About

Jason is designed to be convenient for reading arbitrary JSON while still honoring the strictness of the language. Inspired by other libraries and improved to work well for common use cases. It currently focuses on reading JSON data rather than creating it. API Documentation can be found on godoc.org.

Install

go get github.com/antonholmquist/jason

Import

import (
  "github.com/antonholmquist/jason"
)

Data types

The following golang values are used to represent JSON data types. It is consistent with how encoding/json uses primitive types.

  • bool, for JSON booleans
  • json.Number/float64/int64, for JSON numbers
  • string, for JSON strings
  • []*Value, for JSON arrays
  • map[string]*Value, for JSON objects
  • nil for JSON null

Examples

Create from bytes

Create object from bytes. Returns an error if the bytes are not valid JSON.

v, err := jason.NewObjectFromBytes(b)

If the root object is unknown or not an object, use NewValueFromBytes instead. It can then be typecasted using one of the conversion methods provided by the library, for instance Array() or String().

v, err := jason.NewValueFromBytes(b)

Create from a reader (like a http response)

Create value from a io.reader. Returns an error if the string couldn't be parsed.

v, err := jason.NewObjectFromReader(res.Body)

Read values

Reading values is easy. If the key path is invalid or type doesn't match, it will return an error and the default value.

name, err := v.GetString("name")
age, err := v.GetInt64("age")
verified, err := v.GetBoolean("verified")
education, err := v.GetObject("education")
friends, err := v.GetObjectArray("friends")
interests, err := v.GetStringArray("interests")

Read nested values

Reading nested values is easy. If the path is invalid or type doesn't match, it will return the default value and an error.

name, err := v.GetString("person", "name")
age, err := v.GetInt64("person", "age")
verified, err := v.GetBoolean("person", "verified")
education, err := v.GetObject("person", "education")
friends, err := v.GetObjectArray("person", "friends")

Loop through array

Looping through an array is done with GetValueArray() or GetObjectArray(). It returns an error if the value at that keypath is null (or something else than an array).

friends, err := person.GetObjectArray("friends")
for _, friend := range friends {
  name, err := friend.GetString("name")
  age, err := friend.GetNumber("age")
}

Loop through object

Looping through an object is easy. GetObject() returns an error if the value at that keypath is null (or something else than an object).

person, err := person.GetObject("person")
for key, value := range person.Map() {
  ...
}

Sample App

Example project:

package main

import (
  "github.com/antonholmquist/jason"
  "log"
)

func main() {

  exampleJSON := `{
    "name": "Walter White",
    "age": 51,
    "children": [
      "junior",
      "holly"
    ],
    "other": {
      "occupation": "chemist",
      "years": 23
    }
  }`

  v, _ := jason.NewObjectFromBytes([]byte(exampleJSON))

  name, _ := v.GetString("name")
  age, _ := v.GetNumber("age")
  occupation, _ := v.GetString("other", "occupation")
  years, _ := v.GetNumber("other", "years")

  log.Println("age:", age)
  log.Println("name:", name)
  log.Println("occupation:", occupation)
  log.Println("years:", years)

  children, _ := v.GetStringArray("children")
  for i, child := range children {
    log.Printf("child %d: %s", i, child)
  }

  others, _ := v.GetObject("other")

  for _, value := range others.Map() {

    s, sErr := value.String()
    n, nErr := value.Number()

    if sErr == nil {
      log.Println("string value: ", s)
    } else if nErr == nil {
      log.Println("number value: ", n)
    }
  }
}

Documentation

Documentation can be found on godoc:

https://godoc.org/github.com/antonholmquist/jason

Test

To run the project tests:

go test

Compatibility

Go 1.1 and up.

Where does the name come from?

I remembered it from an email one of our projects managers sent a couple of years ago.

"Don't worry. We can handle both XML and Jason"

Author

Anton Holmquist, http://twitter.com/antonholmquist

jason's People

Contributors

antonholmquist avatar bahlo avatar fly avatar manbeardo avatar ms-xy avatar mtiller avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jason's Issues

Idea: NewObject with Go values

First: We use this library at work in almost every service and really love it! ๐ŸŽ‰

But we sometimes need to create Jason objects to call functions which expect them.
What do you think of a func to create objects via Go values? We're currently just marshalling via encoding/json and importing to jason with NewObjectFromBytes, but I'm sure there's a better and more performant way to achieve this.

If you're ok with this, I'm happy to create a PR.
My idea would be something like jason.NewObject(map[string]interface{}) *jason.Object.
What do you think?

Keep up the good work ๐Ÿ’ช

Highly nested Json

Hi,

I've a highly nested Json that I want to iterate through. Here is an example.

[{"a":[{"3":5},{"2":3},{"b":[{"n":2},{"b":"c"},{"c":[{"d":1},{"u":2}]}]}]},{"a":[{"3":5},{"2":3},{"b":[{"n":2},{"b":"c"},{"c":[{"d":1},{"f":[[2,3,4,{"tik":1}],3,5]}]}]}]},{"a":[{"3":5},{"2":3},{"b":[{"n":2},{"b":"c"},{"c":[{"d":1},{"i":2}]}]}]}]

Ho do I get to the tik key?

Also probably an unrelated question, is there a way how to search this highly nested Json based on key or value?

Thank you

thank you!

after doing so much json parsing with interface {} directly this is wonderful.

Variadic GetString

This throws an error:
// components is an array of keys, first two elements being some internal values
var children []string
children=components[2:]
value,err:=v.GetString(children...)

However, this works:
value,err:=v.GetString(children[0],children[1],[children[2])

Am I doing something wrong?

data

If the amount of data to 50kb, performance testing will be very slow๏ผŸ

Setting values

It would be nice to have an API that also allowed mutation. Any interest?

Would you accept a pull request with such functionality?

Remove "idiomatic" from the repo description

While this library does present an interesting and totally valid alternative, it's not idiomatic at all. The most common approach (by far) is to just use the encoding/json package. This includes parsing arbitrary data, as detailed in the JSON and Go blog post.

multiple-value v.GetString() in single-value context

package main

import (
	"fmt"
	"github.com/antonholmquist/jason"
)

func main() {

	data := []byte(`{
		"hits":{
			"total":2,
			"max_score":4.631368,
			"hits":[
				{
					"_source":{
						"account_number":298,
						"balance":34334,
						"firstname":"Bullock",
						"lastname":"Marsh"
					}
				},
				{
					"_source":{
						"account_number":25,
						"balance":40540,
						"firstname":"Virginia",
						"lastname":"Ayala"
					}
				}
			]
		}
	}`)

	js, _ := jason.NewObjectFromBytes(data)

	//get total
	total, _ := js.GetInt64("hits", "total")
	fmt.Println(total)

	//get _source list
	hitsjson, _ := js.GetObjectArray("hits", "hits")
	for _, v := range hitsjson {
		fmt.Printf("%v\n", v.GetString("_source", "firstname"))
	}
}

error:

multiple-value v.GetString() in single-value context

THANK YOU FOR THIS LIB!

You're a lifesaver. The default package is easy to use with short snippets of json; but, this makes working with large json files a dream. Thank you so much.

README Wrong

json.NewValueFromString / NewValueFromReader are used around the README but don't appear to exist.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.