I am a .NET guy. Very much new to the Go language.
In .NET we have extension methods. Is there anything equivalent in Go?
In .NET I will do like bsonTrans["trans.ticket"]
in that bsonTrans => bson document
"trans.ticket" => key in json
trans is outer level and
ticket is inner level
I am using native mongodb driver. In that I add my extension functions to perform these operations.
Like wise up to the nth level I did it .NET.
I would like to apply the same logic in Go.
Example
b := []byte(trans)
var config map[string]interface{}
err := json.Unmarshal(b, &config)
fmt.Println(config["data"].(map[string] interface{})["issued"])
For instance in that example, can i do something like:
config["data.issued"] which should give the value in return ?
Please help me in figuring this out...
Actual json :-
(The actual json is too big, however I am providing a sample of it with less fields.)
{
"_id" : 2001,
"address" : {
"line1" : "",
"line2" : "",
"line3" : ""
},
"tickets" : [
{
"seq" : 2,
"add" : [
{
"seq" : "",
"amnt" : 50
},
{
"seq" : "",
"amnt" : 50
{
"seq" : "",
"amnt" : 50
}
}
}
]
}
Reason for not using struct is my json has too many nested structures and I have more than 10 schemas with different structures.
So I left out structs.
I admit that I am not sure that omitting structs is the best way.
Extension methods are not supported the way it is in .NET.
The closest thing you can do is create a type from string and create a method on that type:
type MyString string
func (m *MyString) Method() {
}
func main() {
var s MyString = ""
s.Method()
}
Your reason for not Unmarshalling into structs is not a good one. You are deliberately avoiding a core language feature out of laziness of defining a few types (in fact, you only need to define what you intend to use), and instead would rather basically re-implement the functionality haphazardly and unsafely yourself?
Try using Go the way it was meant to be used. You just might like it.
Here is a sample of code that uses your json. Your json sample wasn't valid, so I corrected it to what I think your intent was.
I think you will find using a map[string]interface{} with a deeply nested struct will not work out, but I don't know your use case, so I can't say for sure.
Here is an interactive link that runs the code as well: http://play.golang.org/p/0gtYMfBMWX
package main
import "fmt"
import "encoding/json"
func main() {
b := []byte(`{
"tickets": [
{
"add": [
{
"amnt": 50,
"seq": ""
},
{
"amnt": 50,
"seq": ""
},
{
"amnt": 50,
"seq": ""
}
],
"seq": 2
}
],
"address": {
"line3": "",
"line2": "",
"line1": ""
},
"_id": 2001
}`)
var config map[string]interface{}
if err := json.Unmarshal(b, &config); err != nil {
fmt.Printf("Error: %s", err)
return
}
// I'm not sure what part of the data you are trying to get at here...
//fmt.Println(config["data"].(map[string]interface{})["issued"])
fmt.Printf("%v
", config)
tickets := config["tickets"]
fmt.Printf("%v
", tickets)
}