Manually reading JSON values

In Go, I usually decouple my JSON into a structure and read values ​​from the structure. It works very well.

This time I only care about a specific element of the JSON object and because the general JSON object is very large, I do not want to create a structure.

Is there a way in Go so that I can search for values ​​in a JSON object using keys or iterating through arrays as usual.

Given the following JSON, how can I pull only a field title.

{
  "title": "Found a bug",
  "body": "I'm having a problem with this.",
  "assignee": "octocat",
  "milestone": 1,
  "labels": [
    "bug"
  ]
}
+4
source share
4 answers

Darigaaz, , . , .

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)

}
+1

, .

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)

}

:

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

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

. .

m := make(map[string]string)

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

fmt.Printf("%#v\n", m)
fmt.Println(m["title"])
+6

go-simplejson

:

js, err := simplejson.NewJson([]byte(`{
  "test": {
    "string_array": ["asdf", "ghjk", "zxcv"],
    "string_array_null": ["abc", null, "efg"],
    "array": [1, "2", 3],
    "arraywithsubs": [{"subkeyone": 1},
    {"subkeytwo": 2, "subkeythree": 3}],
    "int": 10,
    "float": 5.150,
    "string": "simplejson",
    "bool": true,
    "sub_obj": {"a": 1}
  }
}`))

if _, ok = js.CheckGet("test"); !ok {
  // Missing test struct
}

aws := js.Get("test").Get("arraywithsubs")
aws.GetIndex(0)
0

: ; , .

():

String s = {json source};
int i = s.indexOf("\"title\": \"")
s.substring(i,s.indexOf("\"",i))

Java

-4

All Articles