Python Forum
Help with a for loop & json...
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with a for loop & json...
#1
Hi everyone,
I'm still stuck trying to get a working function to iterate through a chunk of json, and add the relevant keys/values to a list or dictionary to be searched/referenced later. From a previous topic I posted, I got a pretty good idea of what I have to do, but I'm having a hard time getting it to work.

Here's some example json:
[{'color': 'purple', 'flavor': 'plum', 'code': 3489, 'instock': 'yes'}]
...
...
[{'color': 'red', 'flavor': 'cherry', 'code': 3327, 'instock': 'yes'}]
In the above example, let's assume there are 100's of lines for different candies... but I only want to pull the "code" (unique id) and "instock" key/values for each line, and store them into a dictionary to be used/referenced later on.
Reply
#2
This is what I came up with, which sort-of works.
   r=requests.get(url + id, headers=h, params=p)
    inbound_dict = {}
    inbound=json.loads(r.text)
    for item in inbound['messages']:
        inbound_dict[item['conversationId']] = item['body']
    print(inbound_dict)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Loop through json file and reset values [SOLVED] AlphaInc 2 2,098 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  Convert string to JSON using a for loop PG_Breizh 3 2,964 Jan-08-2021, 06:10 PM
Last Post: PG_Breizh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020