yorkie
yorkie copied to clipboard
Recommendation on converting JSON to Yorkie Document
Hi
This isn't an enhancement request more of a "best way" question.
Currently I have a JSON document and I need to feed that into Yorkie (via Go). I know in JS/TS it's possible to effectively add a JSON object via a single function (update, I believe) but haven't seen anything similar for Go.
I'm currently using the code:
func makeYorkieDoc(data []byte, root *json.Object) error {
var stuff map[string]interface{}
err := json2.Unmarshal(data, &stuff)
if err != nil {
log.Fatalf("Error unmarshalling: %v\n", err)
}
populateObject(root, stuff)
return nil
}
func populateArray(doc *json.Array, a []interface{}) {
for _, v := range a {
switch v.(type) {
case bool:
doc.AddBool(v.(bool))
case []byte:
doc.AddBytes(v.([]byte))
case int64:
doc.AddLong(v.(int64))
case time.Time:
doc.AddDate(v.(time.Time))
case int:
doc.AddInteger(v.(int))
case float32, float64:
doc.AddDouble(v.(float64))
case string:
doc.AddString(v.(string))
case map[string]interface{}:
log.Fatalf("BOOM have object in array... unsure this is allowed!!!\n")
case []interface{}:
newArray := doc.AddNewArray()
populateArray(newArray, v.([]interface{}))
default:
fmt.Printf("I don't know about type %T!\n", v)
}
}
}
func populateObject(doc *json.Object, m map[string]interface{}) {
for k, v := range m {
switch v.(type) {
case bool:
doc.SetBool(k, v.(bool))
case []byte:
doc.SetBytes(k, v.([]byte))
case int64:
doc.SetLong(k, v.(int64))
case time.Time:
doc.SetDate(k, v.(time.Time))
case int:
doc.SetInteger(k, v.(int))
case float32, float64:
doc.SetDouble(k, v.(float64))
case string:
doc.SetString(k, v.(string))
case map[string]interface{}:
newMap := doc.SetNewObject(k)
populateObject(newMap, v.(map[string]interface{}))
case []interface{}:
newArray := doc.SetNewArray(k)
populateArray(newArray, v.([]interface{}))
default:
fmt.Printf("I don't know about type %T!\n", v)
}
}
}
And so far seems to be working fine. Am wondering if there is a recommended alternative to the above?
To clarify, I originally created concrete structs and read the JSON into those and then converted those to Yorkie entities... but the Go layer I'm working on doesn't really need to know the contents... it's just a thin layer (which in this case is just feeding the JSON in).
Thanks for your reporting.
It would be convenient if we could define data using literals available in each SDK's language without individual method calls in Document.update
. In JS SDK, we can define data using literals in Document.update
(https://yorkie.dev/docs/js-sdk#editing-the-document).
Please, feel free to submit a PR for this.