我正在读取 .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
将附加到 slice 中,无论您是否填充其内容(字段)还是不是。
我建议的最简单的解决方案是正常解码,然后对 slice 进行后处理:根据您的要求删除元素。这会产生干净的代码,您可以在将来轻松调整/更改它。虽然它可以作为自定义 slice 类型 []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,跟踪您当前在对象树中的位置,并且当检测到必须排除的对象时,不要处理/将其添加到您的 slice 中。有关如何编写的详细信息和想法,请查看此答案:Go - Decode JSON as it is still streaming in via net/http
关于json - 从键值对中提取 "filtering"JSON 对象的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52491791/