doufan6033 2018-11-29 10:30
浏览 935
已采纳

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

This question already has an answer here:

I want to do the read and write operation in the json file. I made a program for this But there is an error which occure while Unmarshalling the datathe code is given below:-

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)
        }
      }
   }
}

It gives me the error of

panic: interface conversion: interface {} is string, not []uint8

goroutine 1 [running]:

main.main()

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

Edited :-

[{
    "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"
}
]
</div>
  • 写回答

1条回答 默认 最新

  • dongyou9818 2018-11-29 11:48
    关注

    I'm here with solution to write JSON in file with append more columns, please follow the below code.

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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