gpt4 book ai didi

json - 如何解码以下 JSON?

转载 作者:IT王子 更新时间:2023-10-29 02:22:22 31 4
gpt4 key购买 nike

我有一个格式为 JSON 的对象

{
"results": [
{
"hits": [
{
"title": "Juliette DELAUNAY",
"author:url": "abc.com"
}
]
}
]
}

为了在我的 go 程序中解码,我制作了以下结构

type results struct{
Result []result `json:"results"`
}

type result struct{
Hits []hit `json:"hits"`
}

type hit struct{
Name string `json:"title"`
Url string `json:"author:url"`
}
var m =make(map[string]string)
var t results

但是当我尝试执行以下操作时,

decoder := json.NewDecoder(resp.Body)


err = decoder.Decode(&t)
if err != nil {
fmt.Println(err)
}


for _,x := range t.Result[0].Hits{
m[x.Name] = x.Url
fmt.Println(x.Name,x.Url)
}

它给出一个运行时错误,指出索引超出范围。我究竟做错了什么?对于给定的 json,我的结构不正确吗?

编辑:我需要解码的 JSON 文件

var jsonStr = []byte(`{"requests":[{"indexName":"recherchepepitesAtoZ","params":"query=x&hitsPerPage=2817&maxValuesPerFacet=42&page=0&facets=%5B%22field_frenchtech_hub_pepite%22%2C%22field_categorie%22%2C%22field_frenchtech_hub_pepite%22%5D&tagFilters="}]}`)
req, err := http.NewRequest("POST", "http://6y0slgl8yj-dsn.algolia.net/1/indexes/*/queries?x-algolia-agent=Algolia%20for%20vanilla%20JavaScript%20(lite)%203.20.4%3Binstantsearch.js%201.10.4%3BJS%20Helper%202.18.0&x-algolia-application-id=6Y0SLGL8YJ&x-algolia-api-key=6832a361e1e1628f8ddb2483623104c6", bytes.NewBuffer(jsonStr))
//req.Header.Set("X-Custom-Header", "application/x-www-form-urlencoded")
req.Header.Set("Content-Type", "application/json")

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()

最佳答案

这是一个稍微修改过的版本,可以在我的机器上运行,然后去 Playground :

GoPlayground

package main

import (
"encoding/json"
"fmt"
"strings"
)

type results struct {
Result []result `json:"results"`
}

type result struct {
Hits []hit `json:"hits"`
}

type hit struct {
Name string `json:"title"`
Url string `json:"author:url"`
}

var m = make(map[string]string)

func main() {
jsonSample := `{
"results": [
{
"hits": [
{
"title": "Juliette DELAUNAY",
"author:url": "abc.com"
}
]
}
]
}`

var t results
decoder := json.NewDecoder(strings.NewReader(jsonSample))

err := decoder.Decode(&t)
if err != nil {
fmt.Println(err)
}

for _, x := range t.Result[0].Hits {
m[x.Name] = x.Url
fmt.Println(x.Name, x.Url)
}
}

关于json - 如何解码以下 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42044448/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com