str() 与 json.dumps()的区别
1 | 'jsonKey': 'jsonValue',"title": "hello world"} data = { |
In fact, I am more interested in their difference in single quote and double quote in output strings. It seems that I already know one difference between them (mentioned above) and whether json.loads() can load the output string.
json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:
1 | 'jsonKey': None} data = { |
But the dumps() would convert None into null making a valid JSON string that can be loaded:
1 | import json |
In fact in (I believe most) implementations of Python, str(object) wraps strings in single quotes, which is not valid JSON.
1 | An example: |
字典转字符串(dict to str)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 # If your dictionary isn't too big maybe str + eval can do the work:
dict1 = {'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }}
str1 = str(dict1)
dict2 = eval(str1)
print dict1==dict2
# You can use ast.literal_eval instead of eval for additional security if the source is untrusted.
import json
# convert to string
input = json.dumps({'id': id })
# load to dict
my_dict = json.loads(input)
字符串转字典(str to dict)
1
2
3
4 # str to dict
In [33]: import ast
In [34]: ast.literal_eval("{'x':1, 'y':2}")
Out[34]: {'x': 1, 'y': 2}
转换已转义的字符串转字典(str to dict)
1 | '{\\"name\\":\\"michael\\"}' a = |
pymongo
根据ObjectId进行查询
1
2 from bson.objectid import ObjectId
[i for i in dbm.neo_nodes.find({"_id": ObjectId(obj_id_to_find)})]
float nan
1 | import math |