如何在python中将字符串转换成json

今天就跟大家聊聊有关如何在python中将字符串转换成json,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

1、通过json来转换:

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)
<type 'dict'>

以上的方式转换是没问题的,但是加入mes的格式为mes = '{"InsId": 2, "name": "lege-happy", "CreationTime": "2019-04-23T03:18:02Z"}'的时候使用json来转换的时候又会发生什么呢?

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)
<ipython-input-7-77264851f35b> in <module>()
----> 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)

所以使用 json 进行转换存在一个潜在的限制:

由于 json 语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号 (官网上有一段描述是 “A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes” ),因此上面的转换是错误的:

通过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)
<type '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)
<type 'dict'>

上面的例子可以看出进行转换的时候不存在使用json转换的问题,但是我们需要注意的是使用eval会存在安全问题,比如:

串型的输入直接计算。比如,她会将'1+1'的计算串直接计算出结果。

In [14]: value = eval(raw_input('please input a value string:'))
please input a value string:2 + 2

In [15]: value
Out[15]: 4

从上面来看,eval功能可谓非常强大,即可以做string与list,tuple,dict之间的类型转换,还可以做计算器使用!更有甚者,可以对她能解析的字符串都做处理,而不顾忌可能带来的后果!所以说eval强大的背后,是巨大的安全隐患!!!

比如说用户恶意输入下面的字符串:

open(r'D://filename.txt', 'r').read()
__import__('os').system('dir')
__import__('os').system('rm -rf /etc/*')

那么eval就会显示你电脑目录结构,读取文件,删除文件等等。如果是格盘等更严重的操作,她也会照做不误!!! 显然这个不符合我们的需求!
通过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)
<type '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)
<type 'dict'>

使用 ast.literal_eval 进行转换既不存在使用 json 进行转换的问题,也不存在使用 eval 进行转换的 安全性问题,因此推荐使用 ast.literal_eval。

我们来看看官方文档怎么描述literal_eval的:

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.
  """

python是什么意思

Python是一种跨平台的、具有解释性、编译性、互动性和面向对象的脚本语言,其最初的设计是用于编写自动化脚本,随着版本的不断更新和新功能的添加,常用于用于开发独立的项目和大型项目。

看完上述内容,你们对如何在python中将字符串转换成json有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。