Reputation: 513
I want to know how to search for a line that has a certain name. This is my .txt file with json:
{"people": [{"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}, {"name": "Larry", "website": "google.com", "from": "Michigan"}, {"name": "Tim", "website": "apple.com", "from": "Alabama"}]}
This is my code
import json
file = open('data.txt', "r")
read = file.read()
y = json.loads(read)
first = y["people"][0]
second = y["people"][1]
third = y["people"][2]
print(y["people"][0]["name"])
That prints out Scott, but is there a way to search the json file for the line with the name Scott? Ive tried print(y["people"]["name": "Scott"]) but that didnt work. I want the output to be {"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}
Upvotes: 3
Views: 1346
Reputation: 13651
You can store the person's information whose name is Scott
in a list.
Python code:
import json
file = open('data.txt', "r")
read = file.read()
y = json.loads(read)
people = y["people"]
lines = [person for person in people if person["name"] == "Scott"]
if len(lines) == 0:
print("Scott is not found")
else:
for line in lines:
print(line)
data.txt
:
{"people": [{"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}, {"name": "Larry", "website": "google.com", "from": "Michigan"}, {"name": "Tim", "website": "apple.com", "from": "Alabama"}]}
Output:
{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}
Upvotes: 1
Reputation: 3419
you can use the builtin filter
function combined with a lambda
expression for the solution.
data={"people": [{"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}, {"name": "Larry", "website": "google.com", "from": "Michigan"}, {"name": "Tim", "website": "apple.com", "from": "Alabama"}]}
print(filter(lambda x:x['name'] == 'Scott',data['people']))
# gives [{'website': 'stackabuse.com', 'from': 'Nebraska', 'name': 'Scott'}]
Upvotes: 0
Reputation: 36999
You can use a list comprehension to filter the list. e.g.
>>> people = y['people']
>>> people_named_scott = [p for p in people if p['name'] == 'Scott']
>>> people_named_scott
[{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]
Upvotes: 5
Reputation: 2992
You could do something like this where it iterates all people and then returns the first person with the matching name.
def getPersonByName(allInfo, name):
for info in allInfo["people"]:
if info["name"] == name:
return info
allInfo = {"people": [{"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}, {"name": "Larry", "website": "google.com", "from": "Michigan"}, {"name": "Tim", "website": "apple.com", "from": "Alabama"}]}
print(getPersonByName(allInfo, "Scott"))
Upvotes: 0
Reputation: 8144
if i understand you correctly, You are trying to print list of json which has name Scott.
print([jobj if jobj['name']=='Scott' for jobj in y['people']])
Upvotes: 0