在 golang 中没有结构的情况下对 JSON 数据进行最小的修改

我有一个 JSON 格式的 solr 响应,如下所示:


 {

  "responseHeader": {

    "status": 0,

    "QTime": 0,

    "params": {

      "q": "solo",

      "wt": "json"

    }

  },

  "response": {

    "numFound": 2,

    "start": 0,

    "docs": [

      {

          <Large nested JSON element>

      },

      {

          <Large nested JSON element>

      }

    ]

  }

}

现在,在我的 Golang 应用程序中,我想快速删除“responseHeader”,以便我可以单独返回“response”。如何在不创建大型结构的情况下做到这一点?


编辑 1

evanmcdonnal 的答案是这个问题的解决方案,但它有一些小的错别字,这是我最终使用的:


var temp map[string]interface{}


if err := json.Unmarshal(body, &temp); err != nil {

    panic(err.Error())

}


result, err := json.Marshal(temp["response"])


慕桂英3389331
浏览 192回答 2
2回答

梦里花落0921

这是一个非常简短的示例,说明如何快速轻松地执行此操作。步骤是; 解组到通用map[string]interface{}然后,假设没有错误,只编组你想要的内部对象。var temp := &map[string]interface{}if err := json.Unmarshal(input, temp); err != nil {&nbsp; &nbsp; &nbsp;return err;}return json.Marshal(temp["response"])

三国纷争

我编写了一个包µjson来做到这一点:在 JSON 文档上执行通用转换而不解组它们。input := []byte(`{&nbsp; "responseHeader": {&nbsp; &nbsp; "status": 0,&nbsp; &nbsp; "QTime": 0,&nbsp; &nbsp; "params": {&nbsp; &nbsp; &nbsp; "q": "solo",&nbsp; &nbsp; &nbsp; "wt": "json"&nbsp; &nbsp; }&nbsp; },&nbsp; "response": {&nbsp; &nbsp; "numFound": 2,&nbsp; &nbsp; "start": 0,&nbsp; &nbsp; "docs": [&nbsp; &nbsp; &nbsp; { "name": "foo" },&nbsp; &nbsp; &nbsp; { "name": "bar" }&nbsp; &nbsp; ]&nbsp; }}`)blacklistFields := [][]byte{&nbsp; &nbsp; []byte(`"responseHeader"`), // note the quotes}b := make([]byte, 0, 1024)err := ujson.Walk(input, func(_ int, key, value []byte) bool {&nbsp; &nbsp; for _, blacklist := range blacklistFields {&nbsp; &nbsp; &nbsp; &nbsp; if bytes.Equal(key, blacklist) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // remove the key and value from the output&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // write to output&nbsp; &nbsp; if len(b) != 0 && ujson.ShouldAddComma(value, b[len(b)-1]) {&nbsp; &nbsp; &nbsp; &nbsp; b = append(b, ',')&nbsp; &nbsp; }&nbsp; &nbsp; if len(key) > 0 {&nbsp; &nbsp; &nbsp; &nbsp; b = append(b, key...)&nbsp; &nbsp; &nbsp; &nbsp; b = append(b, ':')&nbsp; &nbsp; }&nbsp; &nbsp; b = append(b, value...)&nbsp; &nbsp; return true})if err != nil {&nbsp; &nbsp; panic(err)}fmt.Printf("%s", b)// Output: {"response":{"numFound":2,"start":0,"docs":[{"name":"foo"},{"name":"bar"}]}}您可以在博客文章中阅读更多相关信息。我把答案放在这里以防其他人可能需要它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go