Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregating JSON objects in Go

I'm making a Go service that gathers JSON objects from different sources and aggregates them in a single JSON object.

I was wondering if there was any way to aggregate the child objects without having to unmarshal and re-marshal them again or having to manually build a JSON string.

I was thinking of using a struct containing the already marshalled parts, such as this:

type Event struct {
    Place     string `json:"place"`
    Attendees string `json:"attendees"`
}

Where Place and Attendees are JSON strings themselves. I'd like to somehow mark them as "already marshalled" so they don't end up as escaped JSON strings but get used as is instead.

Is there any way to achieve this?

like image 392
Jukurrpa Avatar asked Apr 08 '26 14:04

Jukurrpa


1 Answers

You can use json.RawMessage

RawMessage is a raw encoded JSON object. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.

Also, json.RawMessage is an alias to []byte so you can values to it this way:

v := json.RawMessage(`{"foo":"bar"}`)

Example:

package main

import (
    "encoding/json"
    "fmt"
)

type Event struct {
    Place     json.RawMessage `json:"place"`
    Attendees json.RawMessage `json:"attendees"`
}

func main() {
    e := Event{
         Place: json.RawMessage(`{"address":"somewhere"}`),
         Attendees: json.RawMessage(`{"key":"value"}`),
    }
    c, err := json.Marshal(&e)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(c))
    // {"place":{"address":"somewhere"},"attendees":{"key":"value"}}
}
like image 142
Asdine Avatar answered Apr 10 '26 03:04

Asdine