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

使用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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?