Hello all,
This question is related to that one
<https://groups.google.com/d/msg/golang-nuts/nIshrMRrAt0/KSnwExJ4DAAJ>
(which gives more detailed motivation).
Assume I have some public type
Person = struct {
PersName: string `json:"name"`
PersPhone: int `json:"phone"`
}
I want to unmarshal (i.e. JSON decode) some JSON, with e.g. the following
rules
a scalar JSON integer is decoded as some Go int64. So Json 123 *⇾* Go
int64(123) etc....
a scalar JSON string is decoded as some Go string. So JSON "abc" *⇾* Go
string("abc") etc...
a JSON object is decoded according to its *first* name:
- when that name is "transl" the corresponding value is a number, and
the decoding is the closure of that mathematical translation
<https://en.wikipedia.org/wiki/Translation_%28geometry%29>. So the JSON {
"transl" : 1 } *⇾* Go closure func(x int) { return x + 1} (of course
the 1 would actually be the binding of a captured variable y in some
closure func(x int) { return x + y }).
- when that name is "strings" the corresponding value is a JSON array of
strings, and its decoding is the slice of such strings. So the JSON {
"strings" : [ "a", "b" ] } *⇾* Go strings slice []string{"a","b"}
- when that name is "name", there is a second name "phone", and its
decoding is the appropriate instance of Person. So the JSON { "name" :
"John Smith", "phone": 1234567 }
*⇾* Go Person{PersName:"John Smith", PersPhone: 1234567}
I don't care for other cases or forms of JSON (in particular other forms of
JSON objects). The decoding (or unmarshaling) could fail (or give some
other value).
How can I achieve that? I believe that I understand how to code the
corresponding encoding. I was thinking of using perhaps some dec
json.Decoder then use dec.Token(), but I am not sure to be able to handle
the Person case (how to parse two fields). It is strange that not every
JSON token is actually publicly visible (colons and commas are not).
Of course the actual case is a bit more complex (and not exactly what I am
explaining above, which is just a simplified example). See my commit
c8a9212eccbdf2
<https://github.com/bstarynk/monimelt/commit/c8a9212eccbdf2fa6f74758c2a0c6c75d1dfaa04>
Thanks for reading.
--
Basile Starynkevitch <http://starynkevitch.net/Basile/> (France)
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.