从键值对中“过滤”出 JSON 对象的最有效方法是什么?

cbl*_*bll 4 json go

我正在阅读一个.json文件。它是一个有效 JSON 格式的对象数组,例如:

    [
        {
                "Id": 13,
                "Location": "Australia",
                "Content": "Another string"
        },
        {
                "Id": 145,
                "Location": "England",
                "Content": "SomeString"
        },
        {
                "Id": 12,
                "Location": "England",
                "Content": "SomeString"
        },
        {
                "Id": 12331,
                "Location": "Sweden",
                "Content": "SomeString"
        },
        {
                "Id": 213123,
                "Location": "England",
                "Content": "SomeString"
        }
     ]
Run Code Online (Sandbox Code Playgroud)

我想过滤掉这些对象 - 例如,删除任何"Location"不等于"England".

到目前为止我尝试过的是创建一个自定义UnmarshalJSON函数。它确实解组了它,但它产生的对象是空的 - 和输入一样多。

示例代码:

type languageStruct struct {
    ID                  int     `json:"Id"`
    Location            string  `json:"Location"` 
    Content             string  `json:"Content"`
}

func filterJSON(file []byte) ([]byte, error) {
    var x []*languageStruct

    err := json.Unmarshal(file, &x)
    check(err)

    return json.MarshalIndent(x, "", " ")
}


func (s *languageStruct) UnmarshalJSON(p []byte) error {

    var result struct {
        ID              int     `json:"Id"`
        Location        string  `json:"Location"` 
        Content         string  `json:"Content"`
    }

    err := json.Unmarshal(p, &result)
    check(err)

    // slice of locations we'd like to filter the objects on
    locations := []string{"England"} // Can be more 

    if sliceContains(s.Location, locations) {
        s.ID = result.ID
        s.Location= result.Location
        s.Content = result.Content
    }

    return nil
}

// helper func to check if a given string, f.e. a value of a key-value pair in a json object, is in a provided list
func sliceContains(a string, list []string) bool {
    for _, b := range list {
        if b == a {
            fmt.Println("it's a match!")
            return true
        }
    }
    return false
}
Run Code Online (Sandbox Code Playgroud)

当这个运行时 - 输出是错误的。它创建尽可能多的对象 - 但是,新对象是空的,fe:

// ...
 [
 {
  "Id": 0,
  "Location": "",
  "Content": ""
 },
 {
  "Id": 0,
  "Location": "",
  "Content": ""
 }
 ]
//...
Run Code Online (Sandbox Code Playgroud)

而我想要的输出,从第一个给定的输入,将是:

[
    {
            "Id": 145,
            "Location": "England",
            "Content": "SomeString"
    },
    {
            "Id": 12,
            "Location": "England",
            "Content": "SomeString"
    },
    {
            "Id": 213123,
            "Location": "England",
            "Content": "SomeString"
    }
 ]
Run Code Online (Sandbox Code Playgroud)

icz*_*cza 5

languageStruct.UnmarshalJSON()被调用时,已经有一个languageStruct准备好的将附加到切片,无论您是否填充其内容(字段)。

最简单也是我建议的解决方案是正常解组,并对切片进行后处理:根据您的要求删除元素。这会产生干净的代码,您可以在将来轻松调整/更改。尽管它可以作为自定义切片类型上的自[]languageStruct定义封送处理逻辑来实现,但我仍然不会为此创建自定义封送处理逻辑,而是将其作为单独的过滤逻辑来实现。

这是一个简单的代码解组、过滤和再次编组(注意:没有定义/使用自定义编组):

var x []*languageStruct

err := json.Unmarshal(file, &x)
if err != nil {
    panic(err)
}

var x2 []*languageStruct
for _, v := range x {
    if v.Location == "England" {
        x2 = append(x2, v)
    }
}

data, err := json.MarshalIndent(x2, "", " ")
fmt.Println(string(data), err)
Run Code Online (Sandbox Code Playgroud)

这将导致您想要的输出。在Go Playground上试一试。

最快和最复杂的解决方案是使用事件驱动的解析和构建状态机,但复杂性会大大增加。这个想法是通过令牌处理 JSON,跟踪您当前在对象树中的位置,并且当检测到必须排除的对象时,不要处理/将其添加到您的切片中。有关如何编写此代码的详细信息和想法,请查看此答案:Go - Decode JSON as it is still in stream in via net/http