Use IF statement to search json file - python

I need to search this json file and print only the peole with a Y status:
[[{"Name": "person1", "Status": "Y"}], [{"Name": "person2", "Status": "N"}], [{"Name": "person3", "Status": "Y"}]]
I can open the file and display the data ok, but need to search within it.
Could someone help complete this if statement for me?
It needs to look at the keyvalue? Status and print only the two people with Y
for name in OpenFile:
**# if Status == Y what do I do here? :**
print ("Name : " +name[i]['Name'])
print ("Status : " +name[i]['Status'])

You need to iterate over the lists, extract the dict from it and check the key 'Status':
for element in OpenFile:
ele = element[0] # grab the dict
if ele.get('Status') == 'Y':
print 'Name: {}'.format(ele.get('Name')
print 'Status: {}'.format(ele.get('Status')
Your OpenFile object is a list of lists, which inside it's dict structure.
So, you want to address the first object in your list (that's the dict) and then perform your check. You do that with ele.get()

It looks like you are referencing [i], while name is your iterator. Change it to something like this:
for name in OpenFile:
**# if Status == Y what do I do here? :**
print ("Name : " +name['Name'])
print ("Status : " +name['Status'])
at the same time, your json formatted data looks like it's formatted like this:
List[list[dict],list[dict],list[dict],] so it'd only make sense to navigate to the Name value like this:
print(OpenFile[0][0]['Name'])
Try if this returns person1 and then base your next if-statement on this.
Additional debugging tool:
use type() to identify how your json is formatted:
type(OpenFile)
type(OpenFile[0])
type(OpenFile[0][0])
etc., use the error to figure out how your json is formatted

Related

Selecting key/value in nested JSON with key which is number stored as string

I have nested JSON file which I can access like this:
jsonObject['results']['query']['1']
I would like to iterate over jsonObject['results']['query'] but when I create loop like this:
for i in range(1,10):
pageNo = '\''+str(i)+'\''
print(pageNo)
print(jsonObject['results']['query'][pageNo])
it gives me error:
KeyError: " '1' "
While line print(pageNo) prints '1' which works fine when I use it in:
jsonObject['results']['query']['1']
What's the catch?

Python removing a comma from last line within a for loop

Id like to know what it takes to remove a comma from the last line within a for loop in python. When I run the script it gives me the below output(after code section). I want to remove the comma at the end of fourth line "{"{#MACRO}":"queue4"}," Please can someone help?
By the way if there is a better way to construct the block please share the ideas. I'm a beginner and like to learn. :)
Code:
import json
import urllib
import string
Url= "http://guest:guest#localhost:55672/api/queues"
Response = urllib.urlopen(Url)
Data = Response.read()
def Qlist(Name):
Text = ''' {{"{{#MACRO}}":"{Name}"}},'''.format(Name=Name)
print Text
X_json = json.loads(Data)
print '''{
"data":['''
for i in X_json:
VV = i['name']
Qlist(VV)
print ''']
}'''
Below is the Output:
{
"data":[
{"{#MACRO}":"queue1"},
{"{#MACRO}":"queue2"},
{"{#MACRO}":"queue3"},
{"{#MACRO}":"queue4"},
]
}
Thanks so much
You can modify your loop as follows.
# Create and initialize a dictionary (Associative Array)
# data['data'] is an empty list.
# Variable name (data in this case) can be anything you want.
# 'data' is a key. notice the quotations around. it's not a variable.
# I used 'data' as the key, becasue you wanted your final output to include that part.
data = {"data": []}
for i in X_json:
# We are not calling the data dictionary here.
# We are accessing the empty list we have created inside the `data` dict (above) using data['data'] syntax.
# We can use the append function to add an item to a list.
# We create a new dictionary for every `name` item found in your json array and
# append that new dictionary to the data['data'] list.
data['data'].append({"{#MACRO}": i['name']})
print(json.dumps(data))
# or print json.dumps(data, indent=True)
Read more about json.dumps() here. You can read more about python's list and dictionary here
Don't print inside Qlist - instead return a value; then you can join all returned values using comma as separator:
def Qlist(Name):
Text = ''' {{"{{#MACRO}}":"{Name}"}}'''.format(Name=Name)
return Text
print '''{
"data":[''' +
',\n'.join([ Qlist(i['name']) for i in X_json ]) +
''']
}'''
And anyway, using json.dumps is likely a better idea.

Python Create a List file and write query

so sorry for my question if it seems so easy but I am newbie user of python and I can not find a way to solve it.
I have a "dish.py" file which includes some sub-lists
Fruits={"Ap":Apple
"Br":Black Mulberry
"Ch":Black Cherry
}
Meals={"BN":Bean
"MT":Meat
"VG":Vegetable
}
Legumes={"LN":Green Lentil
"P": Pea
"PN":Runner Peanut
}
I want to impelement the dish.py file in a code that at the end, I want to create a query inside of the file
with open("/home/user/Py_tut/Cond/dish.py", 'r') as dish:
content = dish.read()
print dish.closed
dm=dict([dish])
nl=[x for x in dm if x[0]=='P']
for x in dm:
x=str(raw_input("Enter word:"))
if x in dm:
print dm[x]
elif x[0]==("P"):
nl.append(x)
print .join( nl)
It may be look so messy but
dm=dict([dish]) I want to create a dictionary for query
nl=[x for x in dm if x[0]=='P'] I want to write words begin with "P" letter
Here is my questions:
1. Q: I suppose there is a problem with my dish.py file. How can I reorganize it?
2. Q: How can I apply a query to the file and extract the words begin with "P"
Thank you so much in advance
dict() can't load strings:
>>> dict("{'a': 1, 'b': 2}")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
dict("{'a': 1, 'b': 2}")
ValueError: dictionary update sequence element 0 has length 1; 2 is required
As a sequence it would be ("{", "'", "a", "'", ":",...
Instead I would use the json module, change the dish.py format (changing extension to .json and using JSON syntax) and change the code.
dish.json
{
"Fruits": {
"Ap": "Apple",
"Br": "Black Mulberry",
"Ch": "Black Cherry"
},
"Meals": {
"BN": "Bean",
"MT": "Meat",
"VG": "Vegetable"
},
"Legumes": {
"GL": "Green Lentin",
"P": "Pea",
"PN": "Running Peanut"
}
}
__init__.py
import json
with open("/home/user/Py_tut/Cond/dish.py", 'r') as dish:
content = dish.read()
print(dish.closed)
dm = json.loads(content) # loads JSON
nl=[x for x in dm if x[0]=='P']
for x in dm:
x = str(raw_input("Enter word:"))
if x in dm:
print dm[x]
elif x[0] == ("P"):
nl.append(x)
print "".join(nl)
Q: How can I apply a query to the file and extract the words begin with "P" Thank you so much in advance
Assuming that you want to get every string separated by either space or newline and return them into a list, i'd do this:
import re #Importing RegExp module
def wordsBeginP():
with open("words.txt") as wordsfile: # Querying a file
words = wordsfile.open
parsed = re.sub(r"\n", " ", words) # Replace \n to " "
return [for i in parsed.split(" ") if i[0] == "P"] # Return list of words
So I think you have more than these two issues/questions.
First, if you want to include 'hardcoded' lists, dicts and such, you probably want to include dish with dish.py being in your working directory.
That is, if your data structures in the python file are actually in the correct form:
Fruits={"Ap":'Apple',
"Br":'Black Mulberry',
"Ch":'Black Cherry'
}
Meals={"BN":'Bean',
"MT":'Meat',
"VG":'Vegetable'
}
Legumes={"LN":'Green Lentil',
"P":'Pea',
"PN":'Runner Peanut'
}
Finally, you can search in all the datastructures that were named and included in the file, under the created namespace of the include (which is dish).
for f in [dish.Fruits,dish.Meals,dish.Legumes]:
for k,v in f.items():
if k.startswith('P'):
print k,v
Also interesting for you might be pickling (though there are some caveats).

Accessing a dictionary within a list within a dictionary

user = code.chan["#example"]["Someuser"]
# user would look something like:
{
'normal': True,
'voiced': False,
'op': False,
'count': 24,
'messages': [
{
'time': 1448847813,
'message': "This is my mesage"
},
{
'time': 1448847818,
'message': "And this is another"
}
]
}
I am trying to get put the items in 'message' into a list to check whether a string matches any of the items.
Let me know if more information is needed.
I guess you want this:
print [i['message'] for i in user['messages']]
Or,
print map(lambda x:x['message'],user['messages'])
Output:
['This is my mesage', 'And this is another']
To print only the last item, you can use negative indexing. Just like below:
print [i['message'] for i in user['messages']][-1]
Output:
And this is another
You can do that like so:
for message in user['messages']:
if some_string == message['message']:
match = True
If you're looking to search through them you'd want to do something like;
if any(search_string in i['message'] for i in user['messages']):
print 'found your query'
Ok i am a bit confused by the question but if i imagined correctly here is my answer.
You have a list of lists and i suspect it is in json format so you need to access it like this
#fetch data
r = requests.get(wherever_you_fetch_them)
s = r.content.decode()
json_resp = json.loads(s)
succ = json_resp['messages']['message']
and you can create a loop, but i cant help you more because i don't know any information about input data.

pymongo no output for query

EDIT:
I have somewhat distilled the question.
mongo_documents = mongo_collection.find({"medicalObjectId": "269"})
print "\n\n"
for this_document in mongo_documents:
print this_document
print "-------------------------"
pqr = 269
mongo_documents2 = mongo_collection.find({"medicalObjectId": pqr})
print "\n\n"
for this_document2 in mongo_documents2:
print this_document2
My problem is that the first code chunk where I use the number as the key in the query, works. But the second chunk where I use the variable, i get no output.
I am a beginner at python and pymongo, so please bear with me.
I have a list as;
row = [1, 2, ...., 100]
I want to query a mongodb collection for each entry in my list.
The collection has the format:
collection = {'pk', 'attribute1', 'attribute2', 'attribute3'}
I want to call the mongodb connection and iterate through each entry in my list with row[i]=pk and return the other attributes as the output.
ie. mongo_documents = mongo_collection.find({'pk' : row[0]})
mongo_documents = mongo_collection.find({'pk' : row[1]})
and so on.
The code that I have is:
for row in result_set:
print row[0]
mongo_documents = mongo_collection.find({'medicalObjectId' : row[0]})
print mongo_documents
for this_document in mongo_documents:
print "----------------------------------"
print this_document
however i get no output. where am I going wrong?
if i print mongo_documents, i get
<pymongo.cursor.Cursor object at 0xe43150>
You could use the $in operator of mongodb to fetch all the rows at once and iterate through them.
mongo_documents = mongo_collection.find({ 'medicalObjectId' : { '$in' : result_set } } );
for doc in mongo_documents:
print mongo_documents
I have not tested it, comment below if it doesnt work.
EDIT
mongo_documents2 = mongo_collection.find({"medicalObjectId": str(pqr)})
print "\n\n"
for this_document2 in mongo_documents2:
print this_document2

Categories