【Python】解析Json
解析Json的常见代码
1 |
|
1. json.loads()
读取字符串到json object
json.loads()
是将str\bytes\bytearray
等格式的文件读取到json object
中。但是在使用的时候往往会因为一些小问题导致读取错误等。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Docstring:
Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
containing a JSON document) to a Python object.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``object_pairs_hook`` is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs. The
return value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders. If ``object_hook``
is also defined, the ``object_pairs_hook`` takes priority.
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg; otherwise ``JSONDecoder`` is used.
链接:https://pan.baidu.com/s/1omzU65YMpJr0jPPFItZ7SA
提取码:ysly
复制这段内容后打开百度网盘手机App,操作更方便哦
上述文件相对常见的Json文件来说,还是有点区别的,用python的json库操作相对有点困难。
报错Expection \,delimiter
,看了好些解决办法仍然没能成功解决:
1 |
|
1 |
|
程序输出
1 |
|
打印了json中categories
对象的值:
[[‘Sports & Outdoors’,
‘Other Sports’,
‘Dance’,
‘Clothing’,
‘Girls’,
‘Skirts’]],
[[‘Sports & Outdoors’, ‘Other Sports’, ‘Dance’]],
[[‘Sports & Outdoors’,
‘Other Sports’,
‘Dance’,
‘Clothing’,
‘Girls’,
‘Skirts’]]
2. 常见错误及解决办法
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Json文件的单双引号不对,如下所示Python中的一个str
,Json中的Key值
都是用单引号'
括起来的,就会报错Expecting property name enclosed in double quotes
:
1 |
|
替换掉str
中的'
为"
,替换/_(空格)
为/
:
1 |
|
再接着读取就不会报错了!!!
1 |
|
结果:
1 |
|
expecting , delimiter
这个问题真的被搞得头疼,到目前还没解决,Json
字段是没有问题的,但是loads()函数
就是会报错
【Python】解析Json
https://hodlyounger.github.io/2023/10/27/B_Code/Python/【Python】解析Json/