简体   繁体   English

python对象和json对象之间有什么区别?

[英]what's the difference between python objects and json objects?

On the surface it appears that python uses json natively. 从表面上看,python本身就使用了json。 The only exception I can think of is the fact that json can store js functions. 我能想到的唯一例外是json可以存储js函数。

Here's my issue: I need to pass json to a python file through the terminal. 这是我的问题:我需要通过终端将json传递给python文件。
Why should or shouldn't I just use eval()? 为什么我应该或不应该只使用eval()?

No, Python does not use JSON natively. 不,Python本身不使用JSON。 This stuff you think is JSON is, in fact, a dictionary, one of many kinds of objects in Python. 你认为这些东西实际上是一个字典, Python中多种对象之一。 The (easy) syntax for building a dictionary in Python is pretty close to JSON but it is incidental. 在Python中构建字典的(简单)语法非常接近JSON,但它是偶然的。 As you can create a dictionary this way: 您可以这样创建字典:

a = {'a' : 2, 'b' : 3}

you can create it this way, too: 你也可以用这种方式创建它:

a = dict([('a', 2), ('b', 3)]);

So, what are the syntaxes so similar? 那么,什么语法如此相似? Well, JSON syntax is inspired by JavaScript syntax for arrays. 好吧,JSON语法的灵感来自于数组的JavaScript语法。 It is likely that the JavaScript syntax also inspired the way Python dictionaries are written or vice versa. JavaScript语法很可能也激发了Python字典的编写方式,反之亦然。 But never assumes these three syntaxes – JavaScript, JSON and Python dicts - to be the same or interchangeable. 但是从不假设这三种语法--JavaScript,JSON和Python dicts - 是相同的或可互换的。

Given that, why should you not use eval() for convert JSON in a dictionary? 鉴于此,为什么不在字典中使用eval()转换JSON? Firstly, because eval() can do anything in Python – such as exiting the program, removing a file, changing some internal data etc. etc. Hence, by using eval() , you might make yourself vulnerable to code injection , depending on how you use it. 首先,因为eval()可以在Python中执行任何操作 - 例如退出程序,删除文件,更改某些内部数据等等。因此,通过使用eval() ,您可能会使自己容易受到代码注入的影响 ,具体取决于你用吧。 Also, using eval() for converting JSON to a dict assumes the syntax of both are identical – which is not necessarily true; 此外,使用eval()将JSON转换为dict假设两者的语法相同 - 这不一定是真的; even if the syntaxes were identical, they cannot be in the future. 即使语法相同,它们也不可能存在。 Finally, there is a much better and more practical way to parse JSON: the json module: 最后,有一种更好,更实用的方法来解析JSON: json模块:

>>> import json
>>> json.loads('{"a":1}')
{'a': 1}

Use it to parse your JSON. 用它来解析你的JSON。

Good luck! 祝好运!

JSON does not have objects per se, and cannot store JavaScript functions. JSON本身没有对象,也无法存储JavaScript函数。 Its syntax may appear similar to JavaScript literals, but trying to use it as such all the time will cause nothing but pain. 它的语法可能看起来类似于JavaScript文字,但尝试一直使用它只会导致痛苦。

And there should be no need to use eval() ; 并且不需要使用eval() ; both JavaScript and Python have JSON parsers and serializers readily available. JavaScript和Python都有JSON解析器和序列化器可供使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM