Home > Mobile >  How to delete object in json
How to delete object in json

Time:10-24

 "Admins": [
        {
            "Admin_name": "admin",
            "Admin_pass": "admin"
        },
        {
            "Admin_name": "administrator",
            "Admin_pass": "password"
        }
    ],
    "Teachers": [
        {
            "Name": "Yersin Zhanabekov",
            "Course": "Physical Culture",
            "Login": "Yersin.Zhanabekov",
            "Pass": "Yersin123",
            "Mark": null
        },
        {
            "Name": "Kayrat Mynbayev",
            "Course": "Theory of Probability and Mathematical Statistics",
            "Login": "Kayrat.Mynbayev",
            "Pass": "Kayrat123",
            "Mark": null
        },
        {
            "Name": "Magzhan Ikram",
            "Course": "Python",
            "Login": "Magzhan .Ikram",
            "Pass": "Magzhan123",
            "Mark": null
        },
        {
            "Name": "Mag",
            "Course": "Python",
            "Login": "Magzhan .Ikram",
            "Pass": "Magzhan123",
            "Mark": null
        }
    ], },
        {
            "Name": "Mag",
            "Course": "Python",
            "Login": "Magzhan",
            "Pass": "Magzhan123",
            "Mark": null
        }
    ],



with open('dict.json', 'r') as rf:
  dataRead = json.load(rf)


log = input("Your username: ")
pas = input("Your password: ")

for name in dataRead['Admins']:
  if log == name['Admin_name'] and pas == name['Admin_pass']:

    y = {'Name': "Hello"}
    dataRead['Teachers'][3]['Name'].pop()
    dataRead['Teachers'][3]['Name'].append(y)

    with open('dict.json', 'w') as rf:
      dataRead = json.dump(dataRead,rf)

I want to delete the object Name, and change it to a new one.With pop() or .delete().

But anyway, I get the same error.

What should I do?

Error is:

Traceback (most recent call last):

dataRead ['Teachers'] [3] ['Name']. pop () AttributeError: 'str' object has no attribute 'pop'

CodePudding user response:

You should just do

dataRead['Teachers'][3]['Name'] = "Hello"

CodePudding user response:

dataRead['Teachers'] is a list. Once you've identified the index of the item in that list that you want to remove (e.g., 3) then dataRead(['Teachers'].pop(3)

CodePudding user response:

You can also look into JSONPath expressions (using libraries like jsonpath-ng). It gives you greater flexibility to navigate through JSON objects. Here are some examples:

changing Name for specific element:

from jsonpath_ng.ext import parser
for match in parser.parse("$.Teachers[?(@.Name=='Mag')]").find(x):
    match.value['Name'] = 'New'

Popping Name from elements with Name attribute:

for match in parser.parse("$.Teachers[?(@.Name)].[*]").find(x):
    match.value.pop('Name')

Setting Name for all nodes in Teachers

for match in parser.parse("$.Teachers.[*]").find(x):
    match.value['Name'] = 'New name'
  • Related