从键值对中"filtering"出 JSON 对象的最有效方法是什么?



我正在阅读.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"
}
]

我想过滤掉这些对象 - 比如说,删除任何"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
}

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

// ...
[
{
"Id": 0,
"Location": "",
"Content": ""
},
{
"Id": 0,
"Location": "",
"Content": ""
}
]
//...

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

[
{
"Id": 145,
"Location": "England",
"Content": "SomeString"
},
{
"Id": 12,
"Location": "England",
"Content": "SomeString"
},
{
"Id": 213123,
"Location": "England",
"Content": "SomeString"
}
]

调用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)

这将产生您想要的输出。在Go Playground上尝试一下。

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

最新更新