0

I have a function that returns an interface{}. How can I serialize this into a JSON Array without "hardcoding" the fields in a struct. I am using https://github.com/jmoiron/jsonq to return the interface.

json.Unmarshal(resp.Bytes(), &response)
data := map[string]interface{}{}
dec := json.NewDecoder(strings.NewReader(resp.String()))
dec.Decode(&data)
jq := jsonq.NewQuery(data)

results, err := jq.Array("results")

if err != nil {
    log.Fatalln("Unable to get results: ", err)
}
if len(results) == 0 {
    return nil
}
return results // this is returning an interface{}
4
  • I don't get the question: you seem to decode JSON stream and then ask how you would serialize (that is, encode) a data structure to a JSON stream. Could you please elaborate? Commented Oct 29, 2017 at 14:50
  • What do you want to do with the data if you don't know what data you get? In the end you are going in circles because at some point down the line you will need to know what data you have in order to use it. If that is not the case (like you just want to write the data as is to some db, file, etc.) then you do not need to unmarshal it in the first place. Commented Oct 29, 2017 at 14:53
  • @kostix I am fetching from an external API that I do not control and I don't want to store all of the data that it's giving me, only a subsection of the JSON response. I plan on storing this in MongoDB or somewhere, but for now I was just trying to print it out in readable form. Really new to Go so I apologize if this question is silly. Commented Oct 29, 2017 at 15:11
  • 1
    Have you tried to just fmt.Println(results)? It should have taken care of that itself ;-) In either case, the stock JSON encoder is fine with accepting interface{}, so you'd just do v, err := json.Marshal(results) to get the []bytes serialization in v. Commented Oct 29, 2017 at 15:39

2 Answers 2

2

a json string can always be unmarshalled to map[string]interface{}. That is what you need to work with then.

Sign up to request clarification or add additional context in comments.

Comments

0

I should have checked the type I was dealing with. I found out by:

fmt.Println(reflect.TypeOf(results))

which returned: []interface {}

I was then able to iterate over it by using:

for _, event:= range results {
        v, err := json.MarshalIndent(event, "", "  ")
        if err != nil {
            fmt.Println("error:", err)
        }
        fmt.Println(string(v))
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.