错误地转换为JSON字符串

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

Incorrectly converts to a JSON string

问题

我正在编写一个API,该API执行查询到OSMR服务器并检索一些数据,尝试将这些数据转换为JSON并在我的API中返回。一切都基本正常工作,但是在结果字符串中,数值被替换为字符"{}"。我不知道发生了什么,我已经在解决这个问题上花了一个小时。

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/url"
    "time"
    "log"
    "bytes"

    "github.com/stretchr/objx"
    "github.com/go-martini/martini"
)

func PrettyJson(data interface{}) (string) {
    buffer := new(bytes.Buffer)
    encoder := json.NewEncoder(buffer)
    encoder.SetIndent("", "    ")

    err := encoder.Encode(data)
    if err != nil {
       return ""
    }
    return buffer.String()
}

func main() {
    app := martini.Classic()

    app.Get("/", func() string {
        return "/"
    })

    app.Get("/routes", func(req *http.Request, res http.ResponseWriter) string {
        query, err := url.ParseQuery(req.URL.RawQuery)
        if err != nil {
            log.Println(err)
        }

        var client = &http.Client{Timeout: 100 * time.Second}

        if v1, v2 := query["src"], query["dst"]; v1 != nil && v2 != nil {
            var routes_array []map[string]interface{}

            for _, destination := range query["dst"] {
                request_url := fmt.Sprintf("http://router.project-osrm.org/route/v1/driving/%s;%s?overview=false", query["src"][0], destination)
                response, err := client.Get(request_url)
                if err != nil {
                    log.Fatal(err)
                    return "{\"message\": \"internal server error\"}"
                }
        
                buf := new(bytes.Buffer)
                buf.ReadFrom(response.Body)
                newStr := buf.String()

                document, _ := objx.FromJSON(newStr)
            
                route := map[string]interface{}{
                    "destination": destination,
                    "distance":    document.Get("routes[0].distance"),
                    "duration":    document.Get("routes[0].duration"),
                }

                routes_array = append(routes_array, route)

            }


            response := map[string]interface{} {
                "source": query["src"],
                "routes": routes_array,
            }
            fmt.Println("ROUTES_ARRAY")
            fmt.Println(routes_array)
            fmt.Println()
            fmt.Println("RESPONSE")
            fmt.Println(response)
            fmt.Println()
            return PrettyJson(response)
        
        }

        return "{\"message\": \"incorrect value of arguments\"}"
    })

    app.Run()

}

我的API的输出:

{
    "routes": [
        {
            "destination": "13.397634,52.529407",
            "distance": {},
            "duration": {}
        },
        {
            "destination": "13.428555,52.523219",
            "distance": {},
            "duration": {}
        }
    ],
    "source": [
        "13.388860,52.517037"
    ]
}

routes_array和response变量的输出:

ROUTES_ARRAY
[map[destination:13.397634,52.529407 distance:1884.8 duration:251.4] 
map[destination:13.428555,52.523219 distance:3795.2 duration:384.5]]
RESPONSE
map[routes:[map[destination:13.397634,52.529407 distance:1884.8 duration:251.4] 
map[destination:13.428555,52.523219 distance:3795.2 duration:384.5]] source: 
[13.388860,52.517037]]
英文:

I am writing an API that performs a query to the OSMR server and retrieves some data, tries to convert this data to JSON and return it in my API, everything works almost fine, but instead of numerical values ​​in the resulting string, it substitutes with the characters "{}". I have no idea what's going on, I've been working on this problem for an hour

package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
"log"
"bytes"
"github.com/stretchr/objx"
"github.com/go-martini/martini"
)
func PrettyJson(data interface{}) (string) {
buffer := new(bytes.Buffer)
encoder := json.NewEncoder(buffer)
encoder.SetIndent("", "    ")
err := encoder.Encode(data)
if err != nil {
return ""
}
return buffer.String()
}
func main() {
app := martini.Classic()
app.Get("/", func() string {
return "/"
})
app.Get("/routes", func(req *http.Request, res http.ResponseWriter) string {
query, err := url.ParseQuery(req.URL.RawQuery)
if err != nil {
log.Println(err)
}
var client = &http.Client{Timeout: 100 * time.Second}
if v1, v2 := query["src"], query["dst"]; v1 != nil && v2 != nil {
var routes_array []map[string]interface{}
for _, destination := range query["dst"] {
request_url := fmt.Sprintf("http://router.project-osrm.org/route/v1/driving/%s;%s?overview=false", query["src"][0], destination)
response, err := client.Get(request_url)
if err != nil {
log.Fatal(err)
return "{\"message\": \"internal server error\"}"
}
buf := new(bytes.Buffer)
buf.ReadFrom(response.Body)
newStr := buf.String()
document, _ := objx.FromJSON(newStr)
route := map[string]interface{}{
"destination": destination,
"distance":    document.Get("routes[0].distance"),
"duration":    document.Get("routes[0].duration"),
}
routes_array = append(routes_array, route)
}
response := map[string]interface{} {
"source": query["src"],
"routes": routes_array,
}
fmt.Println("ROUTES_ARRAY")
fmt.Println(routes_array)
fmt.Println()
fmt.Println("RESPONSE")
fmt.Println(response)
fmt.Println()
return PrettyJson(response)
}
return "{\"message\": \"incorrect value of arguments\"}"
})
app.Run()
}

Output from my API

 {
"routes": [
{
"destination": "13.397634,52.529407",
"distance": {},
"duration": {}
},
{
"destination": "13.428555,52.523219",
"distance": {},
"duration": {}
}
],
"source": [
"13.388860,52.517037"
]
}

routes_array and response variable output

ROUTES_ARRAY
[map[destination:13.397634,52.529407 distance:1884.8 duration:251.4] 
map[destination:13.428555,52.523219 distance:3795.2 duration:384.5]]
RESPONSE
map[routes:[map[destination:13.397634,52.529407 distance:1884.8 duration:251.4] 
map[destination:13.428555,52.523219 distance:3795.2 duration:384.5]] source: 
[13.388860,52.517037]]

答案1

得分: 1

一个objx.Value被编组为一个空对象,因为该类型没有任何导出字段。

使用Data方法获取底层值。编组底层值。

route := map[string]interface{}{
"destination": destination,
"distance":    document.Get("routes[0].distance").Data(),
"duration":    document.Get("routes[0].duration").Data(),
}
英文:

An objx.Value is marshaled to an empty object because the type does not have any exported fields.

Use the Data method to get the underlying value. Marshal the underlying value.

route := map[string]interface{}{
"destination": destination,
"distance":    document.Get("routes[0].distance").Data(),
"duration":    document.Get("routes[0].duration").Data(),
}

huangapple
  • 本文由 发表于 2021年6月29日 01:42:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/68167880.html
匿名

发表评论

匿名网友

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

确定