[英]Multi line comma separated list in JSon -Parse with Python
I have a json file which I was parsing to read some attributes which looks like below.我有一个 json 文件,我正在解析它以读取一些如下所示的属性。
"controls": {
"PS": {
"name": "Physical Security",
"level_name": [
"PS 1",
"PS 2"
],
"cost": [
6,
10
],
"ind_cost": [
2,
2
],
"flow": [
0.55,
0.325
]
},
.
.
.
}
Previously when I had only one level like only "PS 1" there was no problem and I was reading the values using this code.以前,当我只有一个级别,例如“PS 1”时,没有问题,我正在使用此代码读取值。
for control in data['controls']:
print(control,': ', data['controls'][control]['name'])
Now, having more than one levels I am having difficulty.现在,有多个级别我遇到了困难。 I tried to split as below.
我尝试如下拆分。
x = data['controls'][control]['name'].split('\n')
or as below或如下
x = data['controls'][control]['name'].split(',')
or as below或如下
x = data['controls'][control]['name'].split('\n,')
Each time I get only one item in x, for this example PS.每次我在 x 中只得到一个项目,对于这个例子 PS。
What I want is to be able to get PS 1 and PS 2 in this order.我想要的是能够按此顺序获得 PS 1 和 PS 2。 Later, I will apply it to cost and other things.. Thanks in advance.
稍后,我会将其应用到成本和其他方面。在此先感谢。
Ferda费尔达
Instead of using:而不是使用:
x = data['controls'][control]['name'].split('\n')
Since you used this loop:由于您使用了此循环:
for control in data['controls']:
control isn't the name, as control refers to: control 不是名称,因为 control 指的是:
data['controls'][---]
as an object, thus if you want to use it, you should instead use:作为 object,因此如果你想使用它,你应该使用:
x = control['name'].split('\n')
Assuming no other issues in the code, this should work.假设代码中没有其他问题,这应该可以工作。 Let me know if you face any issues with that!
如果您遇到任何问题,请告诉我!
Edit 1:编辑1:
Noting the error mentioned, control was told to be a string, however this means one of two things:注意到提到的错误,控制被告知是一个字符串,但这意味着两件事之一:
Thinking of this, it would mean that control would include all the JSON inside it eg考虑到这一点,这意味着控制将包括其中的所有 JSON 例如
print(control)
Output: "name": "Physical Security",
"level_name": [
"PS 1",
"PS 2"
],
"cost": [
6,
10
],
"ind_cost": [
2,
2
],
"flow": [
0.55,
0.325
]
},
Option 2) You need to re-parse your result选项 2)您需要重新解析结果
I can't think of why/if this would happen, but if you have a valid JSON as your output you might just simply need to re-parse it the same way you parsed the original (I assume you are using the standard JSON libary?)我想不出为什么/是否会发生这种情况,但是如果你有一个有效的 JSON 作为你的 output 你可能只需要像你解析原始文件一样重新解析它(我假设你使用的是标准 Z0ECD111C1D7A28748A lib Z0ECD111C1D7A28748 ?)
It was my mistake, I used name instead of level_name.这是我的错误,我使用 name 而不是 level_name。 The below code solved my problem.
下面的代码解决了我的问题。
x = data['controls'][control]['level_name']
for control_level in x:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.