简体   繁体   中英

How to convert Amazon Ion object to JSON object in Go Lang?

I'm looking for a way to convert the Amazon Ion object to JSON in Go Lang. This problem came while I was implementing a DAO layer for Amazon QLDB. What I've done so far is using a Go Struct with both json and ion aliases as follows.

type Passport struct {
   ID      string `json:"id" ion:"id"`
   Name    string `json:"name" ion:"name"`
   Address string `json:"address" ion:"address"`
}

But I'm looking a way to parse Ion to Jason in run time without having static struct definitions. It would be great if you can share an util or existing library to parse ion-to-json.

Thanks in advance.

Note: I have seen few libraries for Python and NodeJs to parse ion-to-json. But I couldn't find an library for Go.

Here you have an implementation of an IonToJson function along with a test.

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
    "testing"

    "github.com/amzn/ion-go/ion"
)

type Passport struct {
    ID      string `json:"id" ion:"id"`
    Name    string `json:"name" ion:"name"`
    Address string `json:"address" ion:"address"`
}

func IonToJson(ionBin []byte) (string, error) {
    var aMap interface{}
    err := ion.Unmarshal(ionBin, &aMap) // unmarshal from ion
    if err != nil {
        return "", fmt.Errorf("Error unmarshaling to golang %s", err)
    }
    b, err := json.Marshal(aMap)
    if err != nil {
        return "", fmt.Errorf("Error marshaling to JSON %s", err)
    }
    return string(b), nil
}

func TestION(t *testing.T) {
    aPassport := Passport{ID: "123", Name: "John", Address: "123 Main St"}
    ionbin, err := ion.MarshalBinary(aPassport) // marshal to ion
    if err != nil {
        t.Fatalf("Error marshaling %s", err)
    }

    jsonResult, err := IonToJson(ionbin)
    if err != nil {
        t.Fatalf("Error marshaling to Json %s", err)
    }

    got := jsonResult
    want := `{"id":"123","name":"John","address":"123 Main St"}`
    areEqual, err := areEqualJSON(got, want)
    if err != nil {
        t.Fatalf("Error comparing JSON %s", err)
    }
    if !areEqual {
        t.Errorf("got %s, want %s", got, want)
    }

}

func areEqualJSON(s1, s2 string) (bool, error) {
    var o1 interface{}
    var o2 interface{}

    var err error
    err = json.Unmarshal([]byte(s1), &o1)
    if err != nil {
        return false, fmt.Errorf("Error mashalling string 1 :: %s", err.Error())
    }
    err = json.Unmarshal([]byte(s2), &o2)
    if err != nil {
        return false, fmt.Errorf("Error mashalling string 2 :: %s", err.Error())
    }

    return reflect.DeepEqual(o1, o2), nil
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM