22 August 2018 ### 如何将JSON中的数字和字符串都解析为数字？

``````var raw = []byte(`{"a":1}`)
var raw_string = []byte(`{"a":"2"}`)
``````

``````type S3 struct {
A json.Number `json:"a"`
}

s3 := new(S3)
err = json.Unmarshal(raw, s3)
log.Println(err, s3.A)

s31 := new(S3)
err = json.Unmarshal(raw_string, s31)
log.Println(err, s31.A)
``````

### 原理

``````// A Number represents a JSON number literal.
type Number string

// String returns the literal text of the number.
func (n Number) String() string { return string(n) }

// Float64 returns the number as a float64.
func (n Number) Float64() (float64, error) {
return strconv.ParseFloat(string(n), 64)
}

// Int64 returns the number as an int64.
func (n Number) Int64() (int64, error) {
return strconv.ParseInt(string(n), 10, 64)
}
``````

### UseNumber

``````decoder := json.NewDecoder(bytes.NewBufferString(`{"10000000000":10000000000,"111":1}`))
decoder.UseNumber()
var obj map[string]interface{}
decoder1.Decode(&obj)
``````

EOF

#### 欢迎加微信交流与吐槽
{"ft_lang_label":"__label__zh","ft_lang_prob":0.732226,"math_prob":0.9924796,"size":1623,"snap":"2021-21-2021-25","text_gpt3_token_len":793,"char_repetition_ratio":0.12476838,"word_repetition_ratio":0.0,"special_character_ratio":0.28650647,"punctuation_ratio":0.140625,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.96837443,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,3,null,9,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-05-13T01:06:56Z\",\"WARC-Record-ID\":\"<urn:uuid:c73fbdef-4e69-4907-af15-201e2a90715c>\",\"Content-Length\":\"23527\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:ce2a35ab-fce8-479e-9457-873e00e5d423>\",\"WARC-Concurrent-To\":\"<urn:uuid:c413f5bd-25e7-4a72-8a5e-e3182cdfa28a>\",\"WARC-IP-Address\":\"185.199.111.153\",\"WARC-Target-URI\":\"https://blog.cyeam.com/golang/2018/08/22/json-number\",\"WARC-Payload-Digest\":\"sha1:Y3UADMQS2OKGQ5HKGJVAFBEXPKZGFAEW\",\"WARC-Block-Digest\":\"sha1:IUW4PAA6LN76FDRDIIQ3AAZXTL4F4NRP\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-21/CC-MAIN-2021-21_segments_1620243991413.30_warc_CC-MAIN-20210512224016-20210513014016-00120.warc.gz\"}"}