Json 在递归golang函数调用中键入

Json 在递归golang函数调用中键入,json,parsing,recursion,go,Json,Parsing,Recursion,Go,我正在为Github上一个名为“数组通配符”的Go项目添加“数组通配符”。下面是我所说的数组通配符的示例: > echo "[{product:'coffee', price:2.10}, {product:'beer', price:3.80}]" | jsonget '*.price' [2.10, 3.80] 我的分行代码是 我遇到的问题是键入,当GetValue遇到*字符时,它会递归,在子表达式上调用GetValue,但类型总是作为字符串返回 例如,在测试文件中,我给它一段j

我正在为Github上一个名为“数组通配符”的Go项目添加“数组通配符”。下面是我所说的数组通配符的示例:

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

[2.10, 3.80]
我的分行代码是

我遇到的问题是键入,当
GetValue
遇到
*
字符时,它会递归,在子表达式上调用
GetValue
,但类型总是作为字符串返回

例如,在测试文件中,我给它一段json:

    {
      "inventory": [
          {"name": "mountain bike", "price": 251.0},
          {"name": "red wagon", "price": 90.10},
          {"name": "kinesis advantage", "price": 300.0},
          {"name": "a ticket to Mars", "price": 1200000000.0}
      ]
    }
然后查询出
存货[*]。价格
,预期为
[251,90.1300,1.2e+09]
,但得到的是
[“251”、“90.1”、“300”、“1.2e+09”]


我想在这里避免使用反射,但我看不到另一种方法

如果我误解了你的问题,我深表歉意,但希望这能有所帮助

我认为您必须使用反射或类型开关(可能在幕后使用反射,对此不确定)

修改现有的
valueToString
函数以包含类型开关应该不会太难。可能将其重命名为
convertValue
或更通用的名称,并在其中添加一个类型开关。如果值是int,则返回int,否则返回字符串

例如:

func convertValue(value interface{}) (text string, i int, err error) { // Was 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:
        i = textBytes
        return nil, i, nil
    }
}
这将很有希望
string()

可能有一种更干净的方法可以做到这一点,但它几乎肯定会涉及到大型代码重构。主要的缺点是,现在需要在使用某个值之前检查该值是否为零

我不确定是否有办法使单个函数能够返回一个不同类型的值,因为我很确定它会破坏类型安全性。如果可能的话,我只能想象通过在函数定义中返回一个空接口来实现。听起来很乱


编辑:查看Andrew Gerrand的博客文章,特别是底部关于解码通用数据的部分。这应该会有帮助。

发布一段代码来突出显示问题会很有帮助。您的库是在
main
包中定义的-您应该修复项目的结构。