doulvli9462
2017-10-22 23:10
浏览 94
已采纳

使用golang将简单的json文件输出到rest api

This is my first go project. All I want to do is read a file.json on my server, then make it available to others via a REST API. But I'm getting errors. Here's what I have so far.

main.go

package main

import (
    "encoding/json"
    "github.com/gorilla/mux"
    "log"
    "net/http"
    "io/ioutil"
    "fmt"
)

func GetDetail(w http.ResponseWriter, r *http.Request) {

    b,_ := ioutil.ReadFile("file.json");

    rawIn := json.RawMessage(string(b))
    var objmap map[string]*json.RawMessage
    err := json.Unmarshal(rawIn, &objmap)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Println(objmap)

    json.NewEncoder(w).Encode(objmap)
}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/detail", GetDetail).Methods("GET")

    log.Fatal(http.ListenAndServe(":8000", router))
}

file.json

{
  favourite_color:"blue",
  attribute:{density:23,allergy:"peanuts",locations:["USA","Canada","Jamaica"]},
  manufacture_year:1998
}

When I run go build; ./sampleproject, then go to my web browser at http://localhost:8000/detail, I get the error message:

invalid character 'f' looking for beginning of object key string map[]

I've tried a few marshal methods, but they all give me different errors. I just need a working example to study from to better understand how all this works.

I should also mention that file.json does not have a fixed schema. It can change drastically at any minute to have a random set of data.

How do I get around the error invalid character f message and get my file.json to render at http://localhost:8000/detail?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongxing4196 2017-10-25 14:04
    已采纳

    As cerise mentioned, it's just formatting error in the JSON file. Must quote all properties.

    Then the rest of the code works

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题