简体   繁体   中英

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.

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

 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.

What I want is to be able to get PS 1 and PS 2 in this order. 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:

data['controls'][---]

as an object, thus if you want to use it, you should instead use:

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:

Noting the error mentioned, control was told to be a string, however this means one of two things:

  1. the JSON isn't parsed correctly due to some error in the format:

Thinking of this, it would mean that control would include all the JSON inside it eg

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

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?)

It was my mistake, I used name instead of level_name. The below code solved my problem.

x = data['controls'][control]['level_name']
        
        
        for control_level in x:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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