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.
Related
I have a JSON file and the inside of it looks like this:
"{'reviewId': 'gp:AOqpTOGiJUWB2pk4jpWSuvqeXofM9B4LQQ4Iom1mNeGzvweEriNTiMdmHsxAJ0jaJiK7CbjJ_s7YEWKE2DA_Qzo', 'userName': '\u00c0ine Mongey', 'userImage': 'https://play-lh.googleusercontent.com/a-/AOh14GhUv3c6xHP4kvLSJLaRaydi6o2qxp6yZhaLeL8QmQ', 'content': \"Honestly a great game, it does take a while to get money at first, and they do make it easier to get money by watching ads. I'm glad they don't push it though, and the game is super relaxing and fun!\", 'score': 5, 'thumbsUpCount': 2, 'reviewCreatedVersion': '1.33.0', 'at': datetime.datetime(2021, 4, 23, 8, 20, 34), 'replyContent': None, 'repliedAt': None}"
I am trying to convert this into a dict and then to a pandas DataFrame. I tried this but it will just turn this into a string representation of a dict, not a dict itself:
with open('sampledict.json') as f:
dictdump = json.loads(f.read())
print(type(dictdump))
I feel like I am so close now but I can't find out what I miss to get a dict out of this. Any input will be greatly appreciated!
If I get your data format correctly, this will work:
with open('sampledict.json') as f:
d = json.load(f)
d = eval(d)
# Or this works as well
d = json.loads(f.read())
d = eval(d)
>>> d.keys()
['userName', 'userImage', 'repliedAt', 'score', 'reviewCreatedVersion', 'at', 'replyContent', 'content', 'reviewId', 'thumbsUpCount']
Are you sure that you have your source JSON correct? The JSON snippet you have provided is a string; it has a " at the start and end. So in its current form getting a string is correct behaviour.
Note also that it is a string representation of a Python dict rather than a JSON object. This is evidenced by the fact that the strings are denoted by single quotes rather than double, and the use of the Python keyword None rather than the JSON null.
If the JSON file were a representative of a plain object then the content would be something of the form:
{
"reviewId": "gp"AO...",
"userName": "...",
"replyContent": null,
"repliedAt": null
}
I.e. the first and last characters are curly braces, not double quotes.
I have a JSON like this in a list agents_json:
[
{
'name': 'ip-10-13-28-114 (5)',
'active': True
},
{
'name': 'ip-10-13-28-127 (6)',
'active': True
},
{
'name': 'ip-10-13-28-127',
'active': True
}
]
I want to delete the objects from the json where the value of the name matches my variable from a list: agents_to_remove it contains strings like the name value of the third object.
So Problem is my list doesn't contain the number between brackets and a lot of objects have names like that.
Can you tell me if its possible to match the json value with a regex in here:
for i in range(len(agents_json)):
for j in agents_to_remove:
regex = re.search(j*)
if agents_json[i]["name"] == j* :
agents_json.pop(i)
break
Obviosly j* isn't working, and after a few hours of searching I still don't have any idea how I could accomplish this.
What you have written looks like JSON - but if this is written in a python file it won't actually be a JSON object, like it might be in javascript, it will be a list of dictionary objects.
It sounds like to want to do some sort of regex or wild card matching to see if an agent in the list appears in the list of agents to be deleted. I don't know exactly what your data looks like but you might try:
remaining_agents = []
for agent in agents_json:
if any(agent["name"].startswith(x) for x in agents_to_remove):
continue
else:
remaining_agents.append(agent)
agents_json = remainig_agents
Here is an alternative to MindOfMetalAndWheels solution, using a regular expression
import re
agents_json = [
{
'name': 'ip-10-13-28-114 (5)',
'active': True
},
{
'name': 'ip-10-13-28-127 (6)',
'active': True
},
{
'name': 'ip-10-13-28-127',
'active': True
}
]
agents_to_remove = ['ip-10-13-28-127']
# Iterate through a copy of the list:
for agent in agents_json[:]:
for regex in agents_to_remove:
if re.search(regex, agent["name"]):
agents_json.remove(agent)
break
print("checking ")
for a in agents_json:
print(a["name"])
i have the below string that i am trying to split into a dictionary with specific names.
string1 = "fdsfsf:?x=klink:apple&nn=specialtime&tr=instruction1&tr=instruction2&tr=instruction3"
what I am hoping to obtain is:
>>> print(dict)
{'namy_names': 'specialtime', 'tracks': ['instruction1', 'instruction2', 'instruction3']}
i'm quite new to working with dictionaries, so not too sure how it is supposed to turn out.
I have tried the below code, but it only provides instruction1 instead of the full list of instructions
delimiters = ['&nn', '&tr']
values = re.split('|'.join(delimiters), string1)
values.pop(0) # remove the initial empty string
keys = re.findall('|'.join(delimiters), string1)
output = dict(zip(keys, values))
print(output)
Use url-parsing.
from urllib import parse
url = "fdsfsf:?x=klink:apple&nn=specialtime&tr=instruction1&tr=instruction2&tr=instruction3"
d = parse.parse_qs(parse.urlparse(url).query)
print(d)
Returns:
{'nn': ['specialtime'],
'tr': ['instruction1', 'instruction2', 'instruction3'],
'x': ['klink:apple']}
And from this point, if necessary..., you would simply have to rename and pick your vars. Like this:
d = {
'namy_names':d.get('nn',['Empty'])[0],
'tracks':d.get('tr',[])
}
# {'namy_names': 'specialtime', 'tracks': ['instruction1', 'instruction2', 'instruction3']}
This looks like url-encoded data, so you can/should use urllib.parse.parse_qs:
import urllib.parse
string1 = "fdsfsf:?x=klink:apple&nn=specialtime&tr=instruction1&tr=instruction2&tr=instruction3"
dic = urllib.parse.parse_qs(string1)
dic = {'namy_names': dic['nn'][0],
'tracks': dic['tr']}
# result: {'namy_names': 'specialtime',
# 'tracks': ['instruction1', 'instruction2', 'instruction3']}
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
Playing with json in Python's STL and came up with this..
import json as j
cred = j.dumps({'Name': 'John Doe', 'Occupation': 'Programmer'},
sort_keys = True,
indent = 4,
separators = (',', ': '))
_f = open('credentials', 'w')
_f.write(cred)
_f.close()
The output is below and all is fine..
{
"Name": "John Doe",
"Occupation": "Programmer"
}
However, i accidentally typed name in lowercase like this..
cred = j.dumps({'name': 'John Doe', 'Occupation': 'Programmer'},
sort_keys = True,
indent = 4,
separators = (',', ': '))
and the result was this..
{
"Occupation": "Programmer",
"name": "John Doe"
}
How does json determine the write/output order of the values passed to it, what precedence does uppercase have over lowercase or vice versa and is there a way to preserve order?
Python dictionaries, as well as JSON objects, do not have an order. Any order you might see is arbitrary and may change at any time. If you want to store order in JSON, you'll need to use an array instead of an object.
sort_keys seems to guarantee some sort of output order, but that's likely only to make it more readable for humans. Computers reading JSON shouldn't care about field order.