【问题标题】:Golang convert json value from int to stringGolang将json值从int转换为字符串
【发布时间】:2018-10-08 16:41:09
【问题描述】:

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

“pk”:145250410

我需要它

“pk”:“145250410”

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

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

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

【问题讨论】:

  • strconv.FormatInt?或者您是否尝试直接作为字符串编组或解组?
  • @JimB 我的整个 json 在 *str.我解组 json 并获取 map[string]interface{}。
  • 不清楚你在问什么。请创建一个minimal reproducible example
  • 你的 json 中有像“0000012345”这样的字符串吗?
  • @Slabgorb 可能是这样的

标签: json go interface


【解决方案1】:
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

【讨论】:

  • 我不知道响应会是什么样的,这就是为什么我不使用结构......这是主要问题
  • 只要 'pk' 键在 json 的顶层,无论 json 的剩余结构如何,这都将起作用。换句话说,你不需要一次解组所有的东西,你可以解组你正在寻找的东西。
  • 我希望这会对你有所帮助,我的 json 看起来像这样:pastebin.com/JgM347zP 在这里你可以看到 pk 是 int 类型,我需要将其转换为 string 类型。这就是我想要实现的目标
  • 这总是只有pk。如果我尝试这个 fmt.Printf("%s", p.PK) 输出是:{000012345} 并且没有其余的 json。
  • 好的,已编辑答案,包括您的 json。其他人可能会想出一种更有效的方式来处理非结构化版本。我试图避免做诸如使用反射之类的事情。我仍然建议不要在您的程序中运行map[string]interface{},这只会让事情变得非常困难。对此有很大改进的一件事是使用两次返回的强制转换来防止由于错误的强制转换造成的随机恐慌。
猜你喜欢
  • 1970-01-01
  • 2019-05-03
  • 1970-01-01
  • 2012-03-24
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-28
相关资源
最近更新 更多