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)
3
  • 1
    Please post the way you tried it. Commented Dec 16, 2020 at 16:02
  • 1
    That's not a dictionary; it's a block of JSON. Commented Dec 16, 2020 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 Commented Dec 16, 2020 at 16:14

2 Answers 2

1

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

del d["functionalGroups"][0]["transactions"][0]["segments"]
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

This one did it as well, thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.