PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 9, 2022

[FIXED] How do I search for a certain line in a json file with a key word?

 July 09, 2022     json, keyword, python, search     No comments   

Issue

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"}


Solution

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'}]


Answered By - a'r
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing