-3

I know there are a lot of questions like these but I am not able to find an answer to my question. Or probably, I am missing something here. The format of my JSON is:

{
    "fields": [
        {
            "type": "long",
            "name": "UniqId",
            "data": "True"
        },
        {
            "type": "string",
            "name": "Name",
            "data": "True"
        },
        {
            "type": "string",
            "name": "Address",
            "data": "False"
        }
    ],
    "type": "struct"
}

I just want name and type to be extracted and appended to a list. First element to be name and second to be type. The above format is saved in a variable json_dump. And when I do:

for k in json_dump1.iteritems():
    print k

It gives me an error

"AttributeError: 'str' object has no attribute 'iteritems".

I would really appreciate the help. Thanks.

petezurich
  • 9,280
  • 9
  • 43
  • 57
Jupyter
  • 131
  • 1
  • 10
  • 2
    You need to use a json parsing library. – Jakob F Feb 20 '20 at 20:13
  • a) are you using Python 2? It's no longer supported, so upgrade if you can. b) you need to deserialise the string with `json.loads()` – roganjosh Feb 20 '20 at 20:13
  • 2
    Your `json_dump1` is a string, it doesn't have `iteritems` as an attribute. You need to parse the string using a json library: ```import json parsed_json = json.loads(json_string)``` – Sami Farhat Feb 20 '20 at 20:14
  • @SamiFarhat please turn your comment into an answer, comments do not allow proper formatting. – Błotosmętek Feb 20 '20 at 20:17
  • 1
    What do/don’t you understand from that error message? Also, **please share a [mcve]**. – AMC Feb 20 '20 at 20:20
  • 1
    Does this answer your question? [How to parse JSON in Python?](https://stackoverflow.com/questions/7771011/how-to-parse-json-in-python) – AMC Feb 20 '20 at 20:20

2 Answers2

2

json_dump1 is a string, so you need to parse it into an object first. This can be done with the json library:

import json
parsed_json = json.loads(json_dump1)

It sounds like you also want to do some comprehension on this. It's unclear exactly how you want the name and type values to be stored, but you would want something like this to iterate over parsed_json:

results = []
for f in parsed_json['fields']:
    results.append(f['name'])
    results.append(f['type'])
calebwoof
  • 100
  • 7
1

For cases like this, it's better to think of the json as a dictionary containing nested lists or dictionaries within them. So if you treat them as such and iterate over the lists/keys you should be fine. In this case, the first key is fields, after that we have a number of lists that each contain a dictionary, so we iterate over each of these lists and extract the desired keys (name and type):

name_list = []
type_list = []
for i in json_file['fields']:
    name_list.append(i['name'])
    type_list.append(i['type'])
print name_list
print type_list

Output:

['UniqId', 'Name', 'Address']
['long', 'string', 'string']

You can also create a dictionary in which you will append these values:

json_values = {'name':type_name,'list':type_list}

Of course you can define this first and append the values to the lists in the dictionaries:

json_values = {'name':[],'list':[]
name_list = []
type_list = []
for i in json_file['fields']:
    json_values['name'].append(i['name'])
    json_values['list'].append(i['type'])
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53