0

我想从(静态模式)json文件中解码大量数据。该文件仅包含数字数据,并且键都是整数。我知道如何将此 json 解码为包含字段map[string]intmap[string]float32使用 json.Unmarshal 的结构。但我对字符串键不感兴趣,我需要以某种方式将它们转换为 int 。

所以我想知道的是:

  1. 有没有办法实现这一点,即直接从解码中获取包含 map[int]float32 类型字段的结构,
  2. 否则如何在解码后以内存有效的方式实现这一点?

谢谢

4

2 回答 2

6

JSON 格式仅使用字符串键指定键/值对象。因此,该encoding/json包也仅支持字符串键。

json/encoding文档指出:

bool,对于 JSON 布尔值
float64,对于 JSON 数字
字符串,对于 JSON 字符串
[]interface{},对于 JSON 数组
map[string]interface{},对于 JSON 对象
nil 对于 JSON null

如果您想使用encoding/json包并将其移动到 map[int]float64,您可以执行以下操作(也适用于 float32):

package main

import (
    "fmt"
    "strconv"
)

func main() {
    a := map[string]float64{"1":1, "2":4, "3":9, "5":25}
    b := make(map[int]float64, len(a))

    for k,v := range a {
        if i, err := strconv.Atoi(k); err == nil {
            b[i] = v
        } else {
            // A non integer key
        }
    }

    fmt.Printf("%#v\n", b)
}

操场

于 2013-08-28T13:25:24.787 回答
0

encoding/json包包括一个Unmarshaler具有单一方法的接口:UnmarshalJSON(data []byte) error.

如果你觉得勇敢,你可以为以下实现:

type IntToFloat map[int]float32

func (itf *IntToFloat) UnmarshalJSON(data []byte) error {
    if itf == nil {
        return errors.New("Unmarshalling JSON for a null IntToFload")
    }
    // MAGIC Goes here.
    return nil
}

编辑

注意:http : //golang.org/src/pkg/encoding/json/decode.go?s=2221:2269#L53 是标准库版本 Unmarshal 的来源。

http://golang.org/pkg/encoding/json/#Unmarshaler是上面引用的接口的来源。

于 2013-08-28T16:07:48.757 回答