-2

I have the following json in this format:

{
    "HATg": {
        "id": "208-2", 
        "code": "225a"
        "state" : True
    }, 
    "PROPEMPTY": {
        "id": "208-3", 
        "code": "225b"
        "state" False
    }
}

Was wondering how do I access/grab both the id and code as I iterate each items in the file in a pythonic way? Like for i in items...

By the way, the contents in the json file differ as it is manipulate by user adding in different contents. Apologize in advance if I am not using any terms as I am not sure what they are called

dissidia
  • 1,531
  • 3
  • 23
  • 53

2 Answers2

1

Assuming your "JSON" looks more like this:

{
    "HATg": {
        "id": "208-2",
        "code": "225a",
        "state": true
    },
    "PROPEMPTY": {
        "id": "208-3",
        "code": "225b",
        "state": false
    }
}

and that you have succesfully parsed it into a Python object (for example, by using j = json.load(jsonfile)), then it's trivial to iterate through it in Python (assuming Python 3):

>>> for key, value in j.items():
...     print("{}: {}, {}".format(key, value['id'], value['code']))
...
PROPEMPTY: 208-3, 225b
HATg: 208-2, 225a
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

What you have here is a python dictionary and not a json. You can iterate them like this:

    a = {
    "HATg": {
        "id": "208-2",
        "code": "225a",
        "state" : True
    },
    "PROPEMPTY": {
        "id": "208-3",
        "code": "225b",
        "state" : False
    }
}

for i in a:
    print i
    print a[i]['id'], a[i]['code']

This will give the output as

PROPEMPTY
208-3 225b
HATg
208-2 225a
thiruvenkadam
  • 4,170
  • 4
  • 27
  • 26