简体   繁体   English

在Python中解析JSON参数中的JSON数据

[英]Parse JSON data in JSON params in Python

Is it possible to load json with json data inside? 可以在内部加载json数据的json吗?

import json
array = '{"container":"{\"foo\":\"bar\"}"}'
data  = json.loads(array)
print(data['container'])

in this code error: json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 17 (char 16) 此代码中的错误:json.decoder.JSONDecodeError:预期为','分隔符:第1行第17列(字符16)

It is possible, but you need more escaping: 可能,但是您需要更多转义:

import json
array = '{"container":"{\\"foo\\":\\"bar\\"}"}'
data = json.loads(array)
print(data['container'])

The problem here was that even in single quoted strings, \\" is an escape sequence for a single quote. The backslash needs to be escaped with another backslash to avoid that. 这里的问题是,即使在单引号字符串中, \\"也是单引号的转义序列。反斜杠需要用另一个反斜杠转义,以避免这种情况。

The following implementation works for me with Python3.6.6. 以下实现对我适用于Python3.6.6。

Code: 码:

import json
array = '{"container":{"foo":"bar"}}'
data = json.loads(array)
print(data['container'])
print(data['container']['foo'])

Output: 输出:

>>> python3 test.py 
{'foo': 'bar'}
bar

NOTE: If you use the comas around in nested Json then the value of container key will be a string not a dict type (after parsing). 注意:如果在嵌套的Json中使用逗号,则container密钥的值将是字符串而不是dict类型(在解析之后)。

Let's see: 让我们来看看:

Code: 码:

import json
array = '{"container":"{\\"foo\\":\\"bar\\"}"}'
data = json.loads(array)
print(data['container'])
print(data['container']['foo'])

Output: 输出:

>>> python3 test.py 
{"foo":"bar"}
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print(data['container']['foo'])
TypeError: string indices must be integers

If you really want to use the comas, you need to parse again the nested Json. 如果您确实要使用逗号,则需要再次解析嵌套的Json。

Like this: 像这样:

Code: 码:

import json
array = '{"container":"{\\"foo\\":\\"bar\\"}"}'
data = json.loads(array)
print(data['container'])
data2 = json.loads(data['container'])
print(data2['foo'])

Output: 输出:

>>> python3 test.py 
{"foo":"bar"}
bar

Try this 尝试这个

import ast
array = '{"container":"{\\"foo\\":\\"bar\\"}"}'

json_data = ast.literal_eval(array)

print(json_data['container'])  

the output will be {'foo':'bar'} 输出将为{'foo':'bar'}

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

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