Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to extract JSON from an http response without having to build structs?

Tags:

json

go

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");

2 Answers

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.

like image 181
Arun G Avatar answered Sep 07 '25 19:09

Arun G


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)
}
like image 32
daplho Avatar answered Sep 07 '25 20:09

daplho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!