英文:
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
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论