如何解决接口{}是字符串,而不是golang中的[] uint8?

时间:2018-11-29 10:30:25

标签: json go unmarshalling

我想在json文件中执行读取和写入操作。我为此编写了一个程序,但是在对数据进行编组时出现错误,代码如下:-

package main

import (
  "encoding/json"
  "fmt"
  "io/ioutil"
)

type Page struct {
  Id           int    `json:"_id" bson:"_id"`
  Title        string `json:"title" bson:"title"`
  Type         string `json:"type" bson:"type"`
  Description  string `json:"description" bson:"description"`
  ProfileImage string `json:"profile_image" bson:"profile_image"`
  DateTime     int64  `json:"date_time" bson:"date_time"`
  Author       string `json:"author" bson:"author"`
  Status       int    `json:"status" bson:"status"`
  Slug         string `json:"slug" bson:"slug"`
}

func main() {
   plan, _ := ioutil.ReadFile("page.json")
   var data interface{}
   err := json.Unmarshal(plan, &data)
   if err != nil {
    fmt.Println(err)
   }
   if sl, ok := data.([]interface{}); ok {
     counter := 0
      for _, val := range sl {
        counter++
        md, _ := val.(map[string]interface{})
        md["_id"] = counter
        fmt.Println(md["_id"])
        for _, k := range md {
            // fmt.Println(k.([]byte))
            rankings := Page{}
            err = json.Unmarshal(k.([]uint8), &rankings)
            if err != nil {
                // nozzle.printError("opening config file", err.Error())
            }

            rankingsJson, _ := json.Marshal(rankings)
            err = ioutil.WriteFile("output.json", rankingsJson, 0644)
            fmt.Printf("%+v", rankings)
        }
      }
   }
}

它给了我

的错误
  

panic:接口转换:interface {}是字符串,而不是[] uint8

     

goroutine 1 [正在运行]:

     

main.main()

     

/home/iron/go/src/test/json_object_read/main.go:38 + 0x545

已编辑:-

[{
    "title": "Home Page",
    "type": "Home Page",
    "description": "On this Page you will get all the little discription about the all sections of the theme.",
    "profile_image": "/home.png",
    "author": "Bookingkoala",
    "status": 1,
    "slug": "home-page"
},
{
    "title": "Booking Page",
    "type": "Booking",
    "description": "On this page you will do Booking in 60 seconds",
    "profile_image": "/Booking.png",
    "author": "Bookingkoala",
    "status": 1,
    "slug": "booking-page"
},
{
    "title":"Gift Cards",
    "type":"Cards",
    "description":"On this page you will get the Gift cards on Special Days like:- Mother Day, Friendship Day, Father Day, etc.",
    "profile_image":"/Gift.jpg",
    "author":"Bookingkoala",
    "status":1,
    "slug":"gift-cards"
},
{
    "title":"Contact Us",
    "type":"Contact Information",
    "description":"On Contact Us Page you will get the Contact information of the merchant.",
    "profile_image":"/Contact.jpg",
    "author":"Bookingkoala",
    "status":1,
    "slug":"contact-us" 
},
{
    "title":"Services",
    "type":"Services",
    "description":"This service page will show you that which services bookingkoala has been provided",
    "profile_image":"/services.jpg",
    "author":"Bookingkoala",
    "status":1,
    "slug":"services"
},
{
    "title":"About Us",
    "type":"About the organisation",
    "description":"Most are targeted towards shareholders and aren't interesting for their customers, but Adidas breaks the mold.While most of the information is still geared towards shareholders, the athletic company's presentation is easily digestible and nicely organized.",
    "profile_image":"/aboutus.jpg",
    "author":"Bookingkoala",
    "status":1,
    "slug":"about-us"
},
{
    "title":"Referrals",
    "type":"referrals",
    "description":"This will give you the money in you wallte on each share.",
    "profile_image":"/referrals.jpg",
    "author":"Bookingkoala",
    "status":1,
    "slug":"referrals"
},
{
    "title":"Login/SignUp",
    "type":"Login/SignUp",
    "description":"Via This page you will enter to the theme.",
    "profile_image":"/login.jpg",
    "author":"Bookingkoala",
    "status":1,
    "slug":"login"
},
{
    "title":"Terms/Services",
    "type":"Terms/Services",
    "description":"This page tells you the term and conditions.",
    "profile_image":"/services_and_terms.jpg",
    "author":"Bookingkoala",
    "status":1,
    "slug":"terms"
},
{
    "title":"Privacy Policy",
    "type":"Privacy Policy",
    "description":"A privacy policy is a legal document that details how a website gathers, stores, shares, and sells data about its visitors. This data typically includes items such as a user's name, address, birthday, marital status, medical history, and consumer behavior. The specific contents of this document depend upon the laws in the legal jurisdiction in which your business operates. Most countries have their own set of guidelines regarding what information is eligible for collection, and how that information may be used.",
    "profile_image":"/privacy.jpg",
    "author":"Bookingkoala",
    "status":1,
    "slug":"privacy-policy"
},
{
    "title":"FAQ",
    "type":"FAQ",
    "description":"This page will Show you frequently ask questions.",
    "profile_image":"/faq.jpg",
    "author":"Bookingkoala",
    "status":1,
    "slug":"faq"
}
]

1 个答案:

答案 0 :(得分:0)

我在这里提供将JSON写入文件并添加更多列的解决方案,请遵循以下代码。

package main

import (
  "encoding/json"
  "fmt"
  "io/ioutil"
)

type Page struct {
  Id           int    `json:"_id" bson:"_id"`
  Title        string `json:"title" bson:"title"`
  Type         string `json:"type" bson:"type"`
  Description  string `json:"description" bson:"description"`
  ProfileImage string `json:"profile_image" bson:"profile_image"`
  DateTime     int64  `json:"date_time" bson:"date_time"`
  Author       string `json:"author" bson:"author"`
  Status       int    `json:"status" bson:"status"`
  Slug         string `json:"slug" bson:"slug"`
}

func main() {
   var data interface{}
   plan, _ := ioutil.ReadFile("page.json")
   err := json.Unmarshal([]byte(plan), &data)
    if err != nil {
        fmt.Println(err)
    }

    var ranking = Page{}
    var rankings = []Page{}
    if sl, ok := data.([]interface{}); ok {
        var counter int = 0

        for _, val := range sl {
            counter = counter + 1
            md, _ := val.(map[string]interface{})
            md["_id"] = counter
            b, err := json.Marshal(md)
            if err != nil {
                panic(err)
            }

            // ********************* Unmarshal *********************
            err = json.Unmarshal(b, &ranking)
            if err != nil {
                fmt.Println(err)
            }

            rankings = append(rankings, ranking)

        }
    }

    rankingsJson, _ := json.Marshal(rankings)
    err = ioutil.WriteFile("output.json", rankingsJson, 0644)
    fmt.Printf("%+v", rankings)
}