Golang将json值从int转换为string

时间:2018-04-27 19:28:45

标签: json go interface

我得到了json的回应。其中有关键的pk和它的值为int。我需要将其转换为字符串,最简单的方法是什么?这是示例

" pk":145250410

我需要它

" pk":" 145250410"

我无法制作模型,并解析它因为我不知道我的json会是什么样的,但我知道它总会有pk,所以这就是我解析它的方式。

var bdoc interface{}
bson.UnmarshalJSON([]byte(gjson.Get(*str, "user").String()), &bdoc)

唯一的问题是我把pk作为int而不是字符串。

1 个答案:

答案 0 :(得分:2)

package main

import (
    "encoding/json"

    "fmt"
    "strconv"
)

var jsonData = []byte(`
{
    "user": {
        "media_count": 2043,
        "follower_count": 663,
        "following_count": 1300,
        "geo_media_count": 0,
        "is_business": false,
        "usertags_count": 423,
        "has_chaining": true,
        "is_favorite": false,
        "has_highlight_reels": true,
        "include_direct_blacklist_status": true,
        "pk": 145250410,
        "username": "karahray",
        "full_name": "K Ray \ud83d\udd35",
        "has_anonymous_profile_picture": false,
        "is_private": false,
        "is_verified": false,
        "profile_pic_url": "",
        "profile_pic_id": "1403809308517206571_145250410",
        "biography": "Austinite, oncology dietitian, lover of food, coffee, beer, scenic jogs, traveling, Los Spurs, my Yorkies and LAUGHING! Fitness/food @LGFTatx!",
        "external_url": "",
        "hd_profile_pic_url_info": {
            "height": 1080,
            "url": "",
            "width": 1080
        },
        "hd_profile_pic_versions": [{
            "height": 320,
            "url": "",
            "width": 320
        }, {
            "height": 640,
            "url": "",
            "width": 640
        }], 
        "reel_auto_archive": "on",
        "school": null,
        "has_unseen_besties_media": false,
        "auto_expand_chaining": false
    },
    "status": "ok"
}`)


// custom json unmarshal
type pk string

func (p *pk) UnmarshalJSON(data []byte) error {
    var tmp int
    if err := json.Unmarshal(data, &tmp); err != nil {
        return err
    }
    *p = pk(strconv.Itoa(tmp))
    return nil
}

type jsonModel struct {
    User struct {
        PK pk `json:"pk"`
    } `json:"user"`
}

func main() {
    // using the custom json unmarshal
    jm := &jsonModel{}
    if err := json.Unmarshal(jsonData, jm); err != nil {
        panic(err)
    }

    // doing it as map[string]interface, then finding the key, 
    // then converting - you end up needing TONS of casting 
    everything := map[string]interface{}{}
    if err := json.Unmarshal(jsonData, &everything); err != nil {
        panic(err)
    }

    var userPart interface{}
    userPart, ok := everything["user"]
    if !ok {
        panic("could not find user key")
    }
    userPartMap := userPart.(map[string]interface{})
    var pkInterface interface{}

    if pkInterface, ok = userPartMap["pk"]; !ok {
        panic("could not find pk key")
    }

    // note that json is going to 'guess' float64 here, so we 
    // need to do a lot of shenanigans.
    pkString := strconv.FormatInt(int64(pkInterface.(float64)),10)

    fmt.Printf("%s\n", jm.User.PK)
    fmt.Printf("%s\n", pkString)


}

输出:

145250410

145250410

https://play.golang.org/p/OfHi0ybHJXE