Home > Blockchain >  How to iterate json list with dict in python
How to iterate json list with dict in python

Time:01-10

I am calling data via an API and want to write that data to my Django model. The API provides me with a JSON with the following structure:

"results": [
        {
            "key1": "value",
            "key2": "value"
         },
         {
            "key1": "value",
            "key2": "value",
         },
         {
            "key1": "value",
            "key2": "value",
         },
         ....

My code looks like this:

    def get_data():
        try:
            response = requests.get(settings.HOST settings.PATH, verify=False)
            for data in response['results']:
                print(data)
                mydata = MyModel.add(**data)
            return results

I get this error:

Connected to pydev debugger (build 212.5284.44)
{'key1': 'value', 'key2': 'value'}
list indices must be integers or slices, not str

Process finished with exit code 0


Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 846, in exec_module
  File "<frozen importlib._bootstrap_external>", line 983, in get_code
  File "<frozen importlib._bootstrap_external>", line 913, in source_to_code
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/Users/user01/Repository/api-test/myapi/myapp/management/commands/getapidata.py", line 27
    get_data()
IndentationError: unexpected unindent
python-BaseException

What I am doing wrong?

A screenshot of the variables in PyCharm

enter image description here

CodePudding user response:

your problem is that you don get the json from response.

like @Jisson said.

you need to call .json()

    def get_data():
        try:
            response = requests.get(settings.HOST settings.PATH, verify=False)
            json_response = response.json() # new
            for data in json_response['results']: # modified
                print(data)
                mydata = MyModel.add(**data)
            return results

CodePudding user response:

My code worked for the most part. Another dict in the json caused the problem. In the model while processing the JSON I did not add another loop and that was the problem. I comment-in this part and all works fine.

Thank you all for you time!

  •  Tags:  
  • Related