Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually read JSON values

Tags:

json

go

In Go I usually unmarshal my JSON into a struct and read values from the struct.. it works very well.

This time around I am only concerned with a certain element of a JSON object and because the overall JSON object is very large, I don't want to have to create a struct.

Is there a way in Go so that I can lookup values in the JSON object using keys or iterate arrays as per usual.

Considering the following JSON how could I pull out the title field only.

{
  "title": "Found a bug",
  "body": "I'm having a problem with this.",
  "assignee": "octocat",
  "milestone": 1,
  "labels": [
    "bug"
  ]
}
like image 983
jim Avatar asked Jun 07 '16 13:06

jim


2 Answers

Dont declare fields you dont want.

https://play.golang.org/p/cQeMkUCyFy

package main

import (
    "fmt"
    "encoding/json"
)

type Struct struct {
    Title   string  `json:"title"`
}

func main() {
    test := `{
        "title": "Found a bug",
        "body": "I'm having a problem with this.",
        "assignee": "octocat",
        "milestone": 1,
        "labels": [
          "bug"
        ]
    }`

    var s Struct
    json.Unmarshal([]byte(test), &s)

    fmt.Printf("%#v", s)

}

Or if you want to completely get rid of structs:

var i interface{}
json.Unmarshal([]byte(test), &i)

fmt.Printf("%#v\n", i)
fmt.Println(i.(map[string]interface{})["title"].(string))

Or. It will swallow all conversion errors.

m := make(map[string]string)

json.Unmarshal([]byte(test), interface{}(&m))

fmt.Printf("%#v\n", m)
fmt.Println(m["title"])
like image 130
Darigaaz Avatar answered Sep 21 '22 22:09

Darigaaz


To extend Darigaaz's answer, you can also use an anonymous struct declared within the parsing function. This avoids having to have package-level type declarations litter the code for single-use cases.

https://play.golang.org/p/MkOo1KNVbs

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    test := `{
        "title": "Found a bug",
        "body": "I'm having a problem with this.",
        "assignee": "octocat",
        "milestone": 1,
        "labels": [
          "bug"
        ]
    }`

    var s struct {
        Title string `json:"title"`
    }
    json.Unmarshal([]byte(test), &s)

    fmt.Printf("%#v", s)

}
like image 32
Kaedys Avatar answered Sep 23 '22 22:09

Kaedys