【问题标题】:how to solve interface {} is string, not []uint8 in golang? [duplicate]如何解决接口{}是字符串,而不是golang中的[]uint8? [复制]
【发布时间】:2018-11-29 10:30:25
【问题描述】:

我想做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"
}
]

【问题讨论】:

  • @Flimzy 你能告诉我如何在我的代码中使用它
  • 如果&ranking 具有string 类型的所有值,则需要从err = json.Unmarshal(k.([]uint8), &rankings) 更改为err = json.Unmarshal(k.(string), &rankings)
  • @saddam 它会显示cannot use k.(string) (type string) as type []byte in argument to json.Unmarshal的错误
  • 告诉我json 的内容是你在page.json 中的内容,我修好了。
  • @saddam 查看 json 文件。我想在文件中写_id字段

标签: json go unmarshalling


【解决方案1】:

我在这里提供了在文件中写入 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)
}

【讨论】:

  • 我更新了代码并删除了jso,它只是用于JSON测试变量。
  • 为我提供这个代码,你让我开心;)
  • 我有一个问题,我们可以使用不同的结构编写多个文件吗?
  • 我认为只有当我们可以写入文件并且当我们将写入另一个结构时,它才会覆盖以前的结构值。
  • 你能告诉我slhere是什么意思
猜你喜欢
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 2013-04-21
相关资源
最近更新 更多