有没有办法在golang中格式化这个json? [英] Is there a way to format this json in golang?

查看:528
本文介绍了有没有办法在golang中格式化这个json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这里是我想要发送的响应结构每个请求到web服务器:

pre $ $ $ $ $

类型HttpResp结构{
状态int`json:status`
描述字符串`json:description`
正文字符串`json:body`
}

以下是我的 articles.go 文件,它们具有获取数据库中所有文章的功能:

 包主

导入(
encoding / json
net / http
log


类型结构{
Id字符串`json:id`
标题字符串`json:title`
正文字符串`json:body`
描述字符串`json:description`
}

func AllArticles(w http.ResponseWriter,r * http。请求){
log.Print(/ articles-GET)
db:= connect()
推迟db.Close()

var articles [] Article
results, err:= db.Query(SELECT * FROM Articles)

if err!= nil {
log.Print(err)
return
}

for results.Next(){
var article Article
err = results.Scan(& article.Title,& article.Description,& article.Body,& article.Id)

if err!= nil {
serr,_:= json.Marshal(err)
json.NewEncoder(w).Encode(HttpResp {Status: 500,Description:无法检索所有文章,Body:string(serr)})
}

articles = append(articles,article)
}
sarr,_:= json.Marshal(articles)

w.Header()。Set(Content-Type,application / json)
json.NewEncoder(w)。 Encode(HttpResp {Status:200,Body:string(sarr)})
}

我面临的问题h
$ b


{status:200,description:,body: [{\id \:\1 \,\title \:\First \,\body \:\This
是一个测试身体,\description \:\This is a test \}]}


我希望身体只是JSON而不是字符串。

解决方案

body 进行编组没有意义, $ C> HttpResp 。相反,将 Body 字段的类型更改为 interface {} ,然后将该字段设置为任何具体类型的值,而不是到一个json字符串,例如 [] Article 然后编组resp一次。

  type HttpResp struct {
Status int`json:status`
描述字符串`json:description`
Body接口{}`json:body`
}

剩下的...

 包主
$ b导入(
encoding / json
net / http
log


类型结构{
Id字符串`json:id`
标题字符串`json:title`
正文字符串`json:body`
描述字符串`json:description`
}

func AllArticles(w http.ResponseWriter,r * http.Request){
log.Print(/文章 - GET)
db:= connect()
defer db.Close()

var articles [] Article
results,err:= db.Query (SELECT * FROM Articles)

if err!= nil {
log.Print(err)
return
}

for results.Next(){
var article Article
err = results.Scan(& article.Title,& article.Description,& article.Body, & article.Id)

if err!= nil {
serr,_:= json.Marshal(err)
json.NewEncoder(w).Encode(HttpResp {状态:500,描述:无法检索所有文章,Body:string(serr)})
}

articles = append(articles,article)
}

w.Header()。Set(Content-Type,application / json)
json.NewEncoder(w).Encode(HttpResp {Status:200,Body:articles})
}


I'm just starting to learn GoLang today, I'm trying to build a simple Rest API Web server.

Here's the response Struct I want to send for each request to the web server :

package main

type HttpResp struct{
    Status      int         `json:"status"`
    Description string      `json:"description"`
    Body        string      `json:"body"`
}

And here's my articles.go file who have the function who gets all the articles in the database :

package main

import (
    "encoding/json"
    "net/http"
    "log"
)

type Article struct{
    Id          string  `json:"id"`
    Title       string  `json:"title"`
    Body        string  `json:"body"`
    Description string  `json:"description"`
}

func AllArticles(w http.ResponseWriter, r *http.Request){
    log.Print("/articles - GET")
    db := connect()
    defer db.Close()

    var articles []Article
    results, err := db.Query("SELECT * FROM Articles")

    if err != nil{
        log.Print(err)
        return
    }

    for results.Next(){
        var article Article
        err = results.Scan(&article.Title, &article.Description, &article.Body, &article.Id)

        if err != nil{
            serr, _ := json.Marshal(err)
            json.NewEncoder(w).Encode(HttpResp{Status: 500, Description: "Failed to retrieve all articles", Body: string(serr)})
        }

        articles = append(articles, article)
    }   
    sarr, _ := json.Marshal(articles)

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(HttpResp{Status: 200, Body: string(sarr)})
}

The issue I'm facing here is that the response is like this :

{"status":200,"description":"","body":"[{\"id\":\"1\",\"title\":\"First\",\"body\":\"This is a test body\",\"description\":\"This is a test\"}]"}

I'd like the body to be just JSON and not a string. How can I acheive that ?

解决方案

No point in marshalling the body separately from the HttpResp. Instead change the Body field's type to interface{} and then set the field to any value of a concrete type as opposed to a json string, e.g. []Article and then marshal the resp once.

type HttpResp struct{
    Status      int         `json:"status"`
    Description string      `json:"description"`
    Body        interface{} `json:"body"`
}

And the rest...

package main

import (
    "encoding/json"
    "net/http"
    "log"
)

type Article struct{
    Id          string  `json:"id"`
    Title       string  `json:"title"`
    Body        string  `json:"body"`
    Description string  `json:"description"`
}

func AllArticles(w http.ResponseWriter, r *http.Request){
    log.Print("/articles - GET")
    db := connect()
    defer db.Close()

    var articles []Article
    results, err := db.Query("SELECT * FROM Articles")

    if err != nil{
        log.Print(err)
        return
    }

    for results.Next(){
        var article Article
        err = results.Scan(&article.Title, &article.Description, &article.Body, &article.Id)

        if err != nil{
            serr, _ := json.Marshal(err)
            json.NewEncoder(w).Encode(HttpResp{Status: 500, Description: "Failed to retrieve all articles", Body: string(serr)})
        }

        articles = append(articles, article)
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(HttpResp{Status: 200, Body: articles})
}

这篇关于有没有办法在golang中格式化这个json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆