python如何将字符串转换成json的几种办法
1、通过json来转换:Python学习交流群:1004391443
In [1]: import json In [2]: mes = '{"InsId": 2, "name": "lege-happy", "CreationTime": "2019-04-23T03:18:02Z"}' In [3]: mes_to_dict = json.loads(mes) In [4]: print type(mes_to_dict)
In [5]: import json In [6]: mes = "{'InsId': 1, 'name': 'lege-error', 'CreationTime': '2019-04-24T03:18:02Z'}" In [7]: mes_to_dict = json.loads(mes) --------------------------------------------------------------------------- ValueError Traceback (most recent call last)in () ----> 1 mes_to_dict = json.loads(mes) /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 336 parse_int is None and parse_float is None and 337 parse_constant is None and object_pairs_hook is None and not kw): --> 338 return _default_decoder.decode(s) 339 if cls is None: 340 cls = JSONDecoder /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.pyc in decode(self, s, _w) 364 365 """ --> 366 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 367 end = _w(s, end).end() 368 if end != len(s): /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.pyc in raw_decode(self, s, idx) 380 """ 381 try: --> 382 obj, end = self.scan_once(s, idx) 383 except StopIteration: 384 raise ValueError("No JSON object could be decoded") ValueError: Expecting property name: line 1 column 2 (char 1)
通过eval来转换:
In [8]: mes = '{"InsId": 2, "name": "lege-happy", "CreationTime": "2019-04-23T03:18:02Z"}' In [9]: mes_dict = eval(mes) In [10]: print type(mes_dict)In [11]: In [11]: mes = mes = "{'InsId': 1, 'name': 'lege-error', 'CreationTime': '2019-04-24T03:18:02Z'}" In [12]: mes_dict = eval(mes) In [13]: print type(mes_dict)
In [14]: value = eval(raw_input('please input a value string:')) please input a value string:2 + 2 In [15]: value Out[15]: 4
open(r'D://filename.txt', 'r').read() __import__('os').system('dir') __import__('os').system('rm -rf /etc/*')
通过literal_eval转换:
In [20]: import ast In [21]: mes = '{"InsId": 2, "name": "lege-happy", "CreationTime": "2019-04-23T03:18:02Z"}' In [22]: mes_dict = ast.literal_eval(mes) In [23]: print type(mes_dict)In [24]: In [24]: In [24]: mes = mes = "{'InsId': 1, 'name': 'lege-error', 'CreationTime': '2019-04-24T03:18:02Z'}" In [25]: mes_dict = ast.literal_eval(mes) In [26]: print type(mes_dict)
def literal_eval(node_or_string): """ Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. """
所以个人推荐大家转换dict的时候,出于安全考虑对字符串进行类型转换的时候,最好使用ast.literal_eval()函数!