Home > OS >  Manipulation of json string in Python
Manipulation of json string in Python

Time:03-06

I have a json string that I need to do some manipulation on it. Here is an example :

{
    "5": ["bigoli", "PASS"],
    "8": ["PASS", "strozzapreti"],
    "10": ["chitarra", "trofie", "PASS"],
    "11": ["spaghetti", "PASS", "linguine", "PASS"],
    "12": ["PASS"],
    "15": ["PASS"],
    "17": ["fusilli", "PASS"]
}

I need to count the value PASS and assign on it a number like PASS1. If two or more PASS are present in key that have consecutive number ( like 1 and 2 or 5 and 6) then the first PASS gets the total number of count and the other are delete. If after that a key has no more value, then it is completely deleted.

The output of the previous example will be :

{
    "5": ["bigoli", "PASS1"],
    "8": ["PASS1", "strozzapreti"],
    "10": ["chitarra", "trofie", "PASS4"],
    "11": ["spaghetti", "linguine"],
    "15": ["PASS1"],
    "17": ["fusilli", "PASS1"]
}

Edit for @Timus : As we can see in the output, the PASS in the key 10 is now PASS4 because it has taken the four occurence of the value from the key 10,11 and 12. Moreover, the key 12 is deleted because is no longer have any value.

So far I have load the data into a dictionnary but I can't figure how to do the iteration part :

import json

jsonStr = '{"5": ["bigoli", "PASS"],"8": ["PASS", "strozzapreti"],"10": ["chitarra", "trofie", "PASS"],"11": ["spaghetti", "PASS", "linguine", "PASS"],"12": ["PASS"],"15": ["PASS"],"17": ["fusilli", "PASS"]}'

dict = json.loads(jsonStr)

Do you have an idea how to do that ?

CodePudding user response:

Here's an attempt:

(1) Convert JSON-string via json.loads into a dictionary data (don't use dict as variable name, you're overwriting a builtin type):

data = json.loads(jsonStr)

(2) Group the keys into groups of consecutive numbers:

keys = sorted(int(key) for key in data.keys())
groups = [[keys[0]]]
group = groups[-1]
for key in keys[1:]:
    if key - 1 == group[-1]:
        group.append(key)
    else:
        groups.append([key])
        group = groups[-1]

Result:

groups = [[5], [8], [10, 11, 12], [15], [17]]

(3) Process the "PASS"es:

for group in groups:
    keys = [str(key) for key in group]
    count = sum(data[key].count("PASS") for key in keys)
    if not count:
        continue
    first = True
    for key in keys:
        values = data[key]
        if first and "PASS" in values:
            data[key][values.index("PASS")]  = str(count)
            first = False
        data[key] = [item for item in values if item != "PASS"]
        if not data[key]:
            del data[key]

Result:

data = {
    '5': ['bigoli', 'PASS1'],
    '8': ['PASS1', 'strozzapreti'],
    '10': ['chitarra', 'trofie', 'PASS4'],
    '11': ['spaghetti', 'linguine'],
    '15': ['PASS1'],
    '17': ['fusilli', 'PASS1']
}

But: Your description is often ambiguous, so I'm not sure this will produce exactly what you want (beyond the sample).

CodePudding user response:

You can use the dict.items() function Like below

import json

jsonStr = '{"5": ["bigoli", "PASS1"],"8": ["PASS1", "strozzapreti"],"10": ["chitarra", "trofie", "PASS4"],"11": ["spaghetti", "linguine"],"15": ["PASS1"],"17": ["fusilli", "PASS1"]}'

dict = json.loads(jsonStr)
print(dict.values())
value_to_find = "PASS1"
counter = 0
for key, value in dict.items():
    if value_to_find in value:
        index_of_value = value.index(value_to_find)
        dict[key][index_of_value] = counter
        counter  = 1
print(dict.items())
  • Related