英文:
Go and JSON: how to dynamically load a field
问题
我知道如何在Go语言中处理JSON和接口,没有太多问题。
我想让用户从JSON字符串中选择一个JSON元素,并将该元素的模式存储在一个字符串中,以便我以后可以动态加载它。
我有以下JSON:
{
"id": 1,
"name": "A green door",
"price": 12.50,
"tags": ["home", "green"]
}
当然,如果我想要JSON的id
元素,这很容易,因为id
是我要保存的字符串。
现在假设我想要tags[1]
。
你可以看到,随着JSON变得越来越复杂,这变得越来越困难。例如,我可能想要保存类似于tags[1].data[0].values.id
的模式,依此类推...
基本上,我需要从我的JSON中获取一个明确定义的元素,并将该模式保存到一个字符串中。
在Go语言中,是否有解决这种问题的方法,而不需要我实现自己的字符串解析器?
英文:
I know how to play with JSON and interfaces in go without too many problems.
I would like to let users choose a JSON element from a JSON string and to store the element pattern in a string so that I can dynamically load it later.
I have the following JSON:
{
"id": 1,
"name": "A green door",
"price": 12.50,
"tags": ["home", "green"]
}
Of course this is easy if I want the id
element of my JSON , as id
is the string I'm going to save.
Now let's say I want tags[1].
You can see this gets harder and harder as the JSON gets more complicated. For example I could want to save a pattern similar to tags[1].data[0].values.id
and so on...
Basically I need to get a well defined element from my JSON and need to save the pattern to a string.
Does GO have a solution to this kind of problem without me implementing my own string parser?
答案1
得分: 1
有几个我能想到的包可以解决这类问题。以下是我能想到的一些例子:
-
github.com/jmoiron/jsonq
jq := jsonq.NewQuery(yourData)
jq.Int("id")
jq.String("tags", "0") -
github.com/araddon/gou
:jh := gou.NewJsonHelper(yourData)
jh.Int("id")
jh.Strings("tags[0]") -
https://github.com/elgs/gojq
这些包非常相似,但函数结构略有不同。
英文:
There are several packages that I can think of that have tools to solve problems like this. Here are some examples off the top of my head:
-
github.com/jmoiron/jsonq
jq := jsonq.NewQuery(yourData)
jq.Int("id")
jq.String("tags", "0") -
github.com/araddon/gou
:jh := gou.NewJsonHelper(yourData)
jh.Int("id")
jh.Strings("tags[0]") -
https://github.com/elgs/gojq
The packages are very similar, but slightly different function structure.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论