Shikloshi Shikloshi - 6 months ago 31
JSON Question

Print function that consumes json.RawMessage directly

I'm doing some work with

Elasticsearch
and the query return a
Source
object which it's type is
*json.RawMessage
.

I only want to print it to screen without creating struct model for it and doing the obvious
json.Marshal
.

Is there a print function that will consume *json.RawMessage type and print it to screen?

Code sample:

for _, hit := range serachResult.Hits.Hits {
fmt.Println(hit.Source, "\n")
}


This code run will result in un-readable array of bytes, apparently without the ability to just build a
string
from the raw message.

Answer

You can use %s to printf:

for _, hit := range serachResult.Hits.Hits {
   fmt.Printf("%s\n", hit.Source)
}