访问具有哈希结构的嵌套JSON文件

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

Accessing nested JSON file with hash structure

问题

我有一个看起来像这样的JSON文件:

{
  "env": {
      "production": {
         "test": {
             "text": "hello"
          },
          "url": {
             "str": "url1"
          }
      },
      "staging": {
         "test": {
             "text": "hel1lo"
          },
          "url": {
             "str": "url31"
          }
      }
   }
}

有没有一种方法可以导入这个文件,并以正确的顺序将其转换为嵌套结构格式,只包括 staging 和其内部字段?

英文:

I have JSON file that looks like this:

{
  "env": {
      "production": {
         "test": {
             "text": "hello"
          },
          "url": {
             "str": "url1"
          }
      },
      "staging": {
         "test": {
             "text": "hel1lo"
          },
          "url": {
             "str": "url31"
          }
      }
   }
}

Is there a way to import this file and get into nested struct format just for staging and its inner fields in correct order?

答案1

得分: 0

虽然我不熟悉Go语言及其JSON工具,但JSON对象被定义为无序的。如果您需要按特定顺序输入数据,您需要使用数组。

根据json.org的说明:

对象是一个无序的名称/值对集合。对象以{(左大括号)开始,以}(右大括号)结束。每个名称后面跟着:(冒号),名称/值对之间用,(逗号)分隔。

数组是一个有序的值集合。数组以[(左方括号)开始,以](右方括号)结束。值之间用,(逗号)分隔。

英文:

While, I'm not familiar with Go and its JSON facilities JSON objects are specified as unordered. If you require your input be in a particular order you'll need to use an array.

From json.org:
> An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
>
>
>
> An array is an ordered collection of values. An array begins with [
> (left bracket) and ends with ] (right bracket). Values are separated
> by , (comma).

答案2

得分: 0

使用以下代码将暂存数据解析为Go值:

type env struct {
  Test struct {
    Text string
  }
  URL struct {
    Str string
  }
}

var v struct {
  Env struct {
    Staging env
  }
}

err := json.Unmarshal(data, &v)
if err != nil {
   // 处理错误
}

staging := v.Env.Staging

playground

JSON对象字段是无序的。Go标准库没有提供一种按源顺序获取对象字段的方法。

英文:

Use this code to parse the staging data to a Go value:

type env struct {
  Test struct {
	Text string
  }
  URL struct {
	Str string
  }
}

var v struct {
  Env struct {
    Staging env
  }
}

err := json.Unmarshal(data, &v)
if err != nil {
   // handle error
}

staging :=  v.Env.Staging

<kbd>playground</kbd>

JSON object fields are unordered. The Go standard library does not provide a way to get object fields in source order.

huangapple
  • 本文由 发表于 2014年10月16日 00:51:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/26387889.html
匿名

发表评论

匿名网友

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

确定