Skip to content

IamFaizanKhalid/jsonq

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

jsonq

jsonq

Go Report Card Release License GoDoc

Easily traverse through the JSON data with no fixed structure.

Installation

go get -u github.com/IamFaizanKhalid/jsonq

Usage Example

See reference docs for more details.

package main

import (
	"fmt"

	"github.com/IamFaizanKhalid/jsonq"
)

func main() {
	apiResponse := []byte(`{
		"code": 200,
		"status": "success",
		"data": {
			"user": {
				"id": 123,
				"name": "John Doe",
				"email": "john@example.com"
			},
			"posts": [
				{
					"id": 1,
					"title": "First Post"
				},
				{
					"id": 2,
					"title": "Second Post"
				}
			]
		}
	}`)

	// parsing the JSON object
	resp, err := jsonq.ParseObject(apiResponse)
	if err != nil {
		panic(err)
	}

	// getting values from the object
	code := resp.Val("code").Int()
	status := resp.Val("status").Str()

	fmt.Println(code, status)

	// checking if the object contains the sub-object
	if !resp.Has("data") {
		return
	}
	data := resp.Obj("data")

	// getting a sub-object which is optional
	userInfo, ok := data.OptObj("user")
	if ok {
		fmt.Println("-- User Info --")

		fmt.Println("ID:", userInfo.Val("id").Int())
		fmt.Println("Name:", userInfo.Val("name").Str())
		fmt.Println("Email:", userInfo.Val("email").Str())
	}

	fmt.Println("-- Posts --")

	// getting array of objects
	posts := data.Arr("posts").Obj()

	for _, post := range posts {
		id := post.Val("id").Int()
		title := post.Val("title").Str()

		fmt.Println(id, title)
	}
}

License

MIT License

About

Easily traverse through the JSON data with no fixed structure.

Topics

Resources

License

Stars

Watchers

Forks

Contributors

Languages