PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 24, 2022

[FIXED] How do i delete an element of a json object with python?

 July 24, 2022     json, python     No comments   

Issue

I'm trying to delete elements from _notes that have _type as 1, but i keep getting an error and I'm not sure what it means, nor do I know how to fix it.. can anyone help me?

My trimmed JSON:

{
    "_notes": [
        {
            "_time": 10,
            "_lineIndex": 2,
            "_lineLayer": 0,
            "_type": 0,
            "_cutDirection": 7
        },
        {
            "_time": 12,
            "_lineIndex": 2,
            "_lineLayer": 0,
            "_type": 1,
            "_cutDirection": 1
        },
        {
            "_time": 14,
            "_lineIndex": 2,
            "_lineLayer": 1,
            "_type": 1,
            "_cutDirection": 0
        }
    ]
}

My python script:

#!/usr/bin/python3

import json
obj = json.load(open("ExpertPlusStandardd.dat"))

for i in range(len(obj["_notes"])):
    print(obj["_notes"][i]["_type"])
    if obj["_notes"][i]["_type"] == 1:
        obj.pop(obj["_notes"][i])

open("test.dat", "w").write(
    json.dumps(obj, indent=4, separators=(',', ': '))
)

Error: Traceback (most recent call last): File "C:\programming\python\train_one_hand\run.py", line 9, in <module> obj.pop(obj["_notes"][i]) TypeError: unhashable type: 'dict'


Solution

It is usually a bad idea to delete from a list that you're iterating. Reverse iterating avoids some of the pitfalls, but it is much more difficult to follow code that does that, so usually you're better off using a list comprehension or filter.

obj["_notes"] = [x for x in obj["_notes"] if x["_type"] != 1]

This gives us the expected output :

{'_notes': 
   [
       {
            '_time': 10, 
            '_lineIndex': 2, 
            '_lineLayer': 0, 
            '_type': 0, 
            '_cutDirection': 7
       }
   ]
}


Answered By - Himanshu Poddar
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing