json - Typing in recursive golang function call -


i working on adding 'array wildcards' go project on github called jsonget. here's example of mean array wildcards:

 > echo "[{product:'coffee', price:2.10}, {product:'beer', price:3.80}]" | jsonget '*.price'  [2.10, 3.80] 

the code branch here

the problem running typing, when getvalue encounters * character, recurses, calling getvalue on subexpression, type comes string.

for example, in test file, give piece of json:

    {       "inventory": [           {"name": "mountain bike", "price": 251.0},           {"name": "red wagon", "price": 90.10},           {"name": "kinesis advantage", "price": 300.0},           {"name": "a ticket mars", "price": 1200000000.0}       ]     } 

then query out inventory[*].price, expecting [251,90.1,300,1.2e+09], instead getting ["251","90.1","300","1.2e+09"].

i avoid using reflection here, don't see way this.

i apologise if i've misunderstood question, helps.

i think you're either going have use reflection or type switch (http://golang.org/doc/effective_go.html#type_switch , uses reflection behind scenes, not sure on that).

it shouldn't hard modify existing valuetostring function include type switch. possibly rename convertvalue or more generic, , put type switch in it. if value int, return int, else return string.

for example:

func convertvalue(value interface{}) (text string, int, err error) { // valuetostring     if value == nil && *printnulls == false {         return "", nil, nil     }      textbytes, err := json.marshal(value)     if err != nil {         return "", nil, err     }     switch value := value.(type) {     default:         text = string(textbytes)         text = quotedstring.replaceallstring(text, "$1")         return text, nil, nil     case int:         = textbytes         return nil, i, nil     } } 

that hopefully string() except values type switch detects ints, returned are.

there's cleaner way of doing it, involve large code refactor. major downside need check if value nil before using it.

i'm not sure if there's way make single function able return 1 value of various types i'm pretty sure play havoc type safety. if possible, can imagine doing returning empty interface in function definition. sounds messy.

edit: check out andrew gerrand's blog post http://blog.golang.org/2011/01/json-and-go.html , bit near bottom decoding generic data. should help.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -