This is one of those subtle differences among various mapping collections that can bite you. JSON treats keys as strings; Python supports distinct keys differing only in type.
In Python (and apparently in Lua) the keys to a mapping (dictionary or table, respectively) are object references. In Python they must be immutable types, or they must be objects which implement a __hash__
method. (The Lua docs suggest that it automatically uses the object's ID as a hash/key even for mutable objects and relies on string interning to ensure that equivalent strings map to the same objects).
In Perl, Javascript, awk and many other languages the keys for hashes, associative arrays or whatever they're called for the given language, are strings (or "scalars" in Perl). In perl $foo{1}, $foo{1.0}, and $foo{"1"}
are all references to the same mapping in %foo
--- the key is evaluated as a scalar!
JSON started as a Javascript serialization technology. (JSON stands for JavaScript Object Notation.) Naturally it implements semantics for its mapping notation which are consistent with its mapping semantics.
如果序列化的两端都是Python,那么最好使用pickles.如果您真的需要将这些从JSON转换回原生Python对象,我想您有两个 Select .首先,如果字典查找失败,您可以try (try: ... except: ...
)将任何键转换为数字.或者,如果您向另一端(JSON数据的序列化程序或生成器)添加代码,那么您可以让它对每个键值执行JSON序列化——将它们作为键列表提供.(然后,Python代码将首先迭代键列表,将它们实例化/反序列化为本机Python对象……然后使用这些对象从映射中访问值).