Go和JSON:如何动态加载字段

huangapple go评论84阅读模式
英文:

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

有几个我能想到的包可以解决这类问题。以下是我能想到的一些例子:

  1. github.com/jmoiron/jsonq

    jq := jsonq.NewQuery(yourData)
    jq.Int("id")
    jq.String("tags", "0")

  2. github.com/araddon/gou:

    jh := gou.NewJsonHelper(yourData)
    jh.Int("id")
    jh.Strings("tags[0]")

  3. 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:

  1. github.com/jmoiron/jsonq

    jq := jsonq.NewQuery(yourData)
    jq.Int("id")
    jq.String("tags", "0")

  2. github.com/araddon/gou:

    jh := gou.NewJsonHelper(yourData)
    jh.Int("id")
    jh.Strings("tags[0]")

  3. https://github.com/elgs/gojq

The packages are very similar, but slightly different function structure.

huangapple
  • 本文由 发表于 2016年11月15日 16:30:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/40605170.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定