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

使用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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误