jsongo

Extracting just a subset of a JSON string in go


I am getting a very long JSON string back from an API.

Basically it looks like this: {"data":{.......},"needs_trial": false, "adjust_time": false,"attempts": 1234}

I need everything inside the data section without the "appendix" as a string.

I have tried to do the usual approach when parsing JSON in Go:

//fetch the data with http.Get into resp.Body

type MyData struct {
   Data map[string]interface{}
}

var data MyData
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
    return err
}

I get the right section of course, but now as a map[string]interface{} obviously. Which I failed to convert back to a string...

Defining the Data field of MyData as string fails too.

I can't just cut it out, because the prefixing part is fixed ({"data":), but trailing isn't.

I can't believe I haven't been able to do this, therefore asking here...I spent already so much time on this, I can take the downvotes...


Solution

  • You can use json.RawMessage which will retain a copy of the raw bytes.

    type MyData struct {
       Data json.RawMessage `json:"data"`
    }
    
    var data MyData
    if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
        return err
    }
    
    dataString := string(data.Data)