解析JSON对象的值

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

Unmarshaling values of JSON objects

问题

可以使用Go的json包来获取edittoken。首先,需要将给定的字符串解析为JSON对象。然后,可以使用点操作符来访问嵌套的属性,以获取edittoken的值。以下是示例代码:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	str := `{
		"query": {
			"pages": {
				"66984": {
					"pageid": 66984,
					"ns": 0,
					"title": "Main Page",
					"touched": "2012-11-23T06:44:22Z",
					"lastrevid": 1347044,
					"counter": "",
					"length": 28,
					"redirect": "",
					"starttimestamp": "2012-12-15T05:21:21Z",
					"edittoken": "bd7d4a61cc4ce6489e68c21259e6e416+\""
				}
			}
		}
	}`

	var data map[string]interface{}
	err := json.Unmarshal([]byte(str), &data)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	edittoken := data["query"].(map[string]interface{})["pages"].(map[string]interface{})["66984"].(map[string]interface{})["edittoken"].(string)
	fmt.Println("edittoken:", edittoken)
}

请注意,上述代码假设给定的字符串是有效的JSON,并且edittoken属性始终存在于相应的位置。如果JSON结构发生变化,代码可能需要进行相应的调整。

英文:

If given the string, from a MediaWiki API request:

str = ` {
    "query": {
        "pages": {
            "66984": {
                "pageid": 66984,
                "ns": 0,
                "title": "Main Page",
                "touched": "2012-11-23T06:44:22Z",
                "lastrevid": 1347044,
                "counter": "",
                "length": 28,
                "redirect": "",
                "starttimestamp": "2012-12-15T05:21:21Z",
                "edittoken": "bd7d4a61cc4ce6489e68c21259e6e416+\\"
            }
        }
    }
}`

What can be done to get the edittoken, using Go's json package (keep in mind the 66984 number will continually change)?

答案1

得分: 5

当你有一个像这样的变化的键时,处理它的最好方法是使用一个映射。在下面的示例中,我使用了结构体,直到我们达到一个变化的键的点。然后我在那之后切换到了映射格式。我也链接了一个可工作的示例。

http://play.golang.org/p/ny0kyafgYO

package main

import (
	"fmt"
	"encoding/json"
)

type query struct {
	Query struct {
		Pages map[string]interface{}
	}
}

func main() {
	str := `{"query":{"pages":{"66984":{"pageid":66984,"ns":0,"title":"Main Page","touched":"2012-11-23T06:44:22Z","lastrevid":1347044,"counter":"","length":28,"redirect":"","starttimestamp":"2012-12-15T05:21:21Z","edittoken":"bd7d4a61cc4ce6489e68c21259e6e416+\"}}}}`

	q := query{}
	err := json.Unmarshal([]byte(str), &q)
	if err != nil {
		panic(err)
	}
	for _, p := range q.Query.Pages {
		fmt.Printf("edittoken = %s\n", p.(map[string]interface{})["edittoken"].(string))
	}
}
英文:

When you have a changing key like this the best way to deal with it is with a map. In the example below I've used structs up until the point we reach a changing key. Then I switched to a map format after that. I linked up a working example as well.

http://play.golang.org/p/ny0kyafgYO

package main

import (
	"fmt"
	"encoding/json"
	)

type query struct {
	Query struct {
		Pages map[string]interface{}
	}
}


func main() {
	str := `{"query":{"pages":{"66984":{"pageid":66984,"ns":0,"title":"Main Page","touched":"2012-11-23T06:44:22Z","lastrevid":1347044,"counter":"","length":28,"redirect":"","starttimestamp":"2012-12-15T05:21:21Z","edittoken":"bd7d4a61cc4ce6489e68c21259e6e416+\\"}}}}`

	q := query{}
	err := json.Unmarshal([]byte(str), &q)
	if err!=nil {
		panic(err)
	}
	for _, p := range q.Query.Pages {
		fmt.Printf("edittoken = %s\n", p.(map[string]interface{})["edittoken"].(string))
	}
}

答案2

得分: 4

请注意,如果您在API请求URL中使用&indexpageids=true参数,结果将包含一个名为“pageids”的数组,如下所示:

str = ` {
    "query": {
        "pageids": [
            "66984"
        ],
        "pages": {
            "66984": {
                "pageid": 66984,
                "ns": 0,
                "title": "Main Page",
                "touched": "2012-11-23T06:44:22Z",
                "lastrevid": 1347044,
                "counter": "",
                "length": 28,
                "redirect": "",
                "starttimestamp": "2012-12-15T05:21:21Z",
                "edittoken": "bd7d4a61cc4ce6489e68c21259e6e416+\\"
            }
        }
    }
}`

因此,您可以使用pageids[0]来访问不断变化的数字,这可能会使事情变得更容易。

英文:

Note that if you use the &indexpageids=true parameter in the API request URL, the result will contain a "pageids" array, like so:

str = ` {
    "query": {
        "pageids": [
            "66984"
        ],
        "pages": {
            "66984": {
                "pageid": 66984,
                "ns": 0,
                "title": "Main Page",
                "touched": "2012-11-23T06:44:22Z",
                "lastrevid": 1347044,
                "counter": "",
                "length": 28,
                "redirect": "",
                "starttimestamp": "2012-12-15T05:21:21Z",
                "edittoken": "bd7d4a61cc4ce6489e68c21259e6e416+\\"
            }
        }
    }
}`

so you can use pageids[0] to access the continually changing number, which will likely make things easier.

huangapple
  • 本文由 发表于 2012年12月15日 13:51:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/13889745.html
匿名

发表评论

匿名网友

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

确定