When restaurants is your list, you have to iterate over this key:
for restaurant in data['restaurants']:
print restaurant['restaurant']['name']
Answer from Daniel on Stack OverflowWhen restaurants is your list, you have to iterate over this key:
for restaurant in data['restaurants']:
print restaurant['restaurant']['name']
with open('data.json') as data_file:
data = json.load(data_file)
for restaurant in data['restaurant']:
print restaurant['restaurant']['name']
This way you will loop over the elements in the list of dictionaries inside your 'restaurants' field and output their names.
You were really close, what you were doing before was looping over all the main fields in your json file and print the name of the first restaurant every time (data['restaurants'][0] gives you the first restaurant in the list of restaurants... and you printed its name every time)
Advice on how to iterate through JSON to find the first instance of a key value pair?
arrays - Issues iterating through JSON list in Python? - Stack Overflow
How do I index an item in a JSON array from Python - Stack Overflow
Looping through JSON
I have an undesirable JSON object that I can't modify:
{
"programs": [
],
"streams": [
{
"index": 0,
"codec_name": "hevc",
"codec_type": "video"
},
{
"index": 1,
"codec_name": "aac",
"codec_type": "audio"
},
{
"index": 2,
"codec_name": "opus",
"codec_type": "audio"
},
{
"index": 3,
"codec_name": "ac3",
"codec_type": "audio"
},
{
"index": 4,
"codec_name": "ass",
"codec_type": "subtitle"
},
{
"index": 5,
"codec_name": "ttf",
"codec_type": "attachment"
}
]
}
This is psudo json from the very real output of ffprobe -loglevel error -show_entries format:stream=index,stream,codec_type,codec_name -of json FILENAME
I need to get the first codec_name from the lowest index of the codec_type: audio.
In this case, index 1, 2, and 3 are all of codec_type: audio, so the lowest index/first instance would be 1 and my codec_name would be aac.
Any ideas on how to move forward on a problem like this? I can't seem to find any stackoverflow threads with anything similar.
----------------------------
EDIT, solution here: https://www.reddit.com/r/learnpython/comments/16af8zf/comment/jz74hc9/?utm_source=share&utm_medium=web2x&context=3
Thank you u/shiftybyte, u/djshadesuk!!!
You are assuming that i is an index, but it is a dictionary, use:
for item in data["Results"]:
print item["Name"]
Quote from the for Statements:
The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Pythonโs for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
you are iterating through the dictionary not indexes so you should either use.
for item in data["Results"]:
print item["Name"]
or
for i in range(len(data["Results"])):
print data["Results"][i]["Name"]
Let jsn is the name of your JSON object:
jsn = {
"users": [
{
"person1": [
{
"money": 769967967456795806758905768494685798974560,
"name": "person1"
}
]
},
{
"person2": [
{
"money": 696969696969969696969696969,
"name": "person2"
}
]
}
]
}
It is a dictionary:
- the key is
"users", its value is a list of (nested) dictionaries, - the second position in this list (counting in Python from 0) is
[1].
So the solution is
>>> jsn["users"][1]
{'person2': [{'money': 696969696969969696969696969, 'name': 'person2'}]}
a better way would be to use enumerate
# not a great way of doing it
>>> index = 0
>>> for value in values:
... print(index, value)
... index += 1
...
0 a
1 b
2 c
# a better more efficient way of doing it using enumerate()
>>> for i, value in enumerate(json["names]):
... print(i, value)
...
0 a
1 b
2 c
Soltution:
data = {
"users": [
{
"person1": [
{
"money": 769967967456795806758905768494685798974560,
"name": "person1"
}
]
},
{
"person2": [
{
"money": 696969696969969696969696969,
"name": "person2"
}
]
}
]
}
for i, name in enumerate(data['users']):
print(i,name)
Output
0 {'person1': [{'money': 769967967456795806758905768494685798974560, 'name': 'person1'}]}
1 {'person2': [{'money': 696969696969969696969696969, 'name': 'person2'}]}
with enumerate, there is much less code.
Then you could do something like person2 = data['users'][1]
The reason why it's printing individual numbers is because the address is a string. Hence, it's not really each number that's being printed, but rather each letter of a string. Consider:
word = "abc"
for letter in word:
print(letter)
# prints:
# a
# b
# c
Therefore, it means somewhere you're assigning individual IP addresses to a variable, and then iterate through that variable (which is a string). Without you providing more code on how you get the ip_address variable, it's hard to say where the problem is.
One way to print your IP addresses (assuming you have them in a dict):
addresses = {"ip_address": [
"192.168.0.1",
"192.168.0.2",
"192.168.0.3"
]}
for address in addresses["ip_address"]: # this gets you a list of IPs
print(address)
Even if you have them somewhere else, the key insight to take away is to not iterate over strings, as you'll get characters (unless that's what you want).
Updated to address edits
Since I do not have the file (is it a file?) you are loading, I will assume I have exact string you posted. This is how you print each individual address with the data you have provided. Note that your situation might be slightly different, because, well, I do not know the full code.
# the string inside load() emulates your message
data = yaml.load('"ip_address": ["192.168.0.1", "192.168.0.2", "192.168.0.3"]')
ip_addresses = data.get('ip_address')
for address in ip_addresses:
print(address)
In your case ip_address = '192.168.0.1'
Are you sure you have the right value in ip_address?
I believe you probably meant:
from __future__ import print_function
for song in json_object:
# now song is a dictionary
for attribute, value in song.items():
print(attribute, value) # example usage
NB: You could use song.iteritems instead of song.items if in Python 2.
Your loading of the JSON data is a little fragile. Instead of:
json_raw= raw.readlines()
json_object = json.loads(json_raw[0])
you should really just do:
json_object = json.load(raw)
You shouldn't think of what you get as a "JSON object". What you have is a list. The list contains two dicts. The dicts contain various key/value pairs, all strings. When you do json_object[0], you're asking for the first dict in the list. When you iterate over that, with for song in json_object[0]:, you iterate over the keys of the dict. Because that's what you get when you iterate over the dict. If you want to access the value associated with the key in that dict, you would use, for example, json_object[0][song].
None of this is specific to JSON. It's just basic Python types, with their basic operations as covered in any tutorial.
I've got my dictionary of scraped data here, I was wondering how I can take this and return the data I want from it?
I just want to return the inner dictionary (so 'links, code, cresturl, name, etc') and I'm a bit confused about the structure of this as I haven't found the right question to google...
edit: well this is a stupid question. How do I return the "teams" list/dictionary specifically? It looks like a dictionary within a list because of the syntax [ { } ]
{
"_links": [
{
"self": "http://api.football-data.org/alpha/soccerseasons/354/teams"
},
{
"soccerseason": "http://api.football-data.org/alpha/soccerseasons/354"
}
],
"count": 20,
"teams": [
{
"_links": {
"fixtures": {
"href": "http://api.football-data.org/alpha/teams/66/fixtures"
},
"players": {
"href": "http://api.football-data.org/alpha/teams/66/players"
},
"self": {
"href": "http://api.football-data.org/alpha/teams/66"
}
},
"code": "MUFC",
"crestUrl": "http://upload.wikimedia.org/wikipedia/de/d/da/Manchester_United_FC.svg",
"name": "Manchester United FC",
"shortName": "ManU",
"squadMarketValue": "425,000,000 \u20ac"
},
{
"_links": {
"fixtures": {
"href": "http://api.football-data.org/alpha/teams/72/fixtures"
},
"players": {
"href": "http://api.football-data.org/alpha/teams/72/players"
},
"self": {
"href": "http://api.football-data.org/alpha/teams/72"
}
},
"code": "SWA",
"crestUrl": "http://upload.wikimedia.org/wikipedia/de/a/ab/Swansea_City_Logo.svg",
"name": "Swansea City",
"shortName": "Swans",
"squadMarketValue": "104,000,000 \u20ac"
},
{
"_links": {
"fixtures": {
"href": "http://api.football-data.org/alpha/teams/338/fixtures"
},
"players": {
"href": "http://api.football-data.org/alpha/teams/338/players"
},
"self": {
"href": "http://api.football-data.org/alpha/teams/338"
}
},
"code": "LCFC",
"crestUrl": "http://upload.wikimedia.org/wikipedia/en/6/63/Leicester02.png",
"name": "Leicester City",
"shortName": "Foxes",
"squadMarketValue": "63,250,000 \u20ac"
},
{
"_links": {
"fixtures": {
"href": "http://api.football-data.org/alpha/teams/62/fixtures"
},
"players": {
"href": "http://api.football-data.org/alpha/teams/62/players"
},
"self": {
"href": "http://api.football-data.org/alpha/teams/62"
}
},
"code": "EFC",
"crestUrl": "http://upload.wikimedia.org/wikipedia/de/f/f9/Everton_FC.svg",
"name": "Everton FC",
"shortName": "Everton",
"squadMarketValue": "179,250,000 \u20ac"
},
.... etc
}
]
}What you're looking at is called 'json'. It's basically xml with javascript friendly syntax.
It's more or less the modern standard for sending data to and from apis. Python has a built in tool to work with it: https://docs.python.org/2/library/json.html
Let's call your data json_raw
import json
json_dict = json.loads(json_raw)
From here json_dict is a python dictionary object that represents that data. It uses dict syntax to access the data:
for example: json_dict['teams'] gets the teams json_dict['teams'][0]['_links']['fixtures']['href'] would return "http://api.football-data.org/alpha/teams/66/fixtures"
you can iterate through dictionaries:
for team in json_dict['teams']:
print team['_links']['fixtures']['href']
should output each fixtures url
edit:
SEE https://gist.github.com/bionikspoon/d7014741472e43f41a25
I was just playing with it. Something sparked my curiosity. But this works.
If your outermost dict is called outer, this will iterate on the inner dicts:
for dct in outer["teams"]:
links = dct["_links"]
code = dct["code"]
# etc...