有没有一种方法可以从http响应中提取JSON,而无需构建结构?

All of the ways I'm seeing involve building structs and unmarshalling the data into the struct. But what if I'm getting JSON responses with hundreds of fields? I don't want to have to create 100 field structs just to be able to get to the data I want. Coming from a Java background there are easy ways to simply get the http response as a string and then pass the JSON string into a JSON object that allows for easy traversal. It's very painless. Is there anything like this in Go?

Java example in pseudo code:

String json = httpResponse.getBody();
JsonObject object = new JsonObject(json); 
object.get("desiredKey");

Golang: fetch JSON from an HTTP response without using structs as helpers

This is a typical scenario we come across. This is achieved by json.Unmarshal.

Here is a simple json

{"textfield":"I'm a text.","num":1234,"list":[1,2,3]}

which is serialized to send across the network and unmarshaled at Golang end.

package main

import (
    "fmt"
    "encoding/json"
)

func main() {
    // replace this by fetching actual response body
    responseBody := `{"textfield":"I'm a text.","num":1234,"list":[1,2,3]}`
    var data map[string]interface{}
    err := json.Unmarshal([]byte(responseBody), &data)
    if err != nil {
        panic(err)
    }
    fmt.Println(data["list"])
    fmt.Println(data["textfield"])
}

Hope this was helpful.

You can as well unmarshal it into a map[string]interface{}

body, err := ioutil.ReadAll(resp.Body)
map := &map[string]interface{}{}
json.Unmarshal(body, map)
desiredValue := map["desiredKey"]

The received json must have an object as the most outer element. The map can also contain lists or nested maps, depending on the json.

The json.Unmarshal method will unmarshal to a struct that does not contain all the fields in the original JSON object. In other words, you can cherry-pick your fields. Here is an example where FirstName and LastName are cherry-picked and MiddleName is ignored from the json string:

package main

import (
  "encoding/json"
  "fmt"
)

type Person struct {
  FirstName string `json:"first_name"`
  LastName  string `json:"last_name"`
}

func main() {
  jsonString := []byte("{\"first_name\": \"John\", \"last_name\": \"Doe\", \"middle_name\": \"Anderson\"}")

  var person Person
  if err := json.Unmarshal(jsonString, &person); err != nil {
    panic(err)
  }

  fmt.Println(person)
}