0

I've got a dictionary that I am trying to remove a specific object.

{
  "authorizationQualifier": "00",
  "testIndicator": " ",
  "functionalGroups": [
    {
      "functionalIdentifierCode": "SC",
      "applicationSenderCode": "6088385400",
      "applicationReceiverCode": "3147392555",
      "transactions": [
        {
          "name": null,
          "transactionSetIdentifierCode": "832",
          "transactionSetControlNumber": "000000001",
          "implementationConventionReference": null,
          "segments": [
            {
              "BCT": {
                "BCT01": "PS",
                "BCT03": "2",
                "id": "BCT"
                     }
             }
           ]
         }
       ]
     }
   ]
}

I'm trying to delete the "segments" list of objects while keeping the functional groups and transactions lists.

I've tried,

ediconverted = open("converted.json", "w")
with open('832.json','r') as jsonfile:
    json_content = json.load(jsonfile)

for element in json_content:
    element.pop('segments', None)

with open('converted.json', 'w') as data_file:
    json_content = json.dump(json_content, data_file)
sal
  • 74
  • 7
  • 1
    Please post the way you tried it. – Harshana Dec 16 '20 at 16:02
  • 1
    That's not a dictionary; it's a block of JSON. – khelwood Dec 16 '20 at 16:03
  • I used loads() to deserialize the json file to a dictionary. Then I can get each list key by using - shortdata = data["functionalGroups"][0]["transactions"][0] (data being the deserialized json file); however I am unclear on how to remove the segments list. Ive tried .pop with no luck – sal Dec 16 '20 at 16:14

2 Answers2

1

For this specific structure, let's name it d, the following will work:

del d["functionalGroups"][0]["transactions"][0]["segments"]
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
1

Assuming you want to remove it for all the groups and transactions:

for g in data["functionalGroups"]: 
    for d in g["transactions"]: 
        d.pop("segments")
        # or, if segments is an optional key
        d.pop("segments", None)

You could do del d["segments"] which has a little less overhead as it does not return anything, but it doesn't offer the option to smoothly handle the case where "segments" is not present (as does dict.pop).

user2390182
  • 72,016
  • 6
  • 67
  • 89