MongoDB python how parse multi-level json [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
how parse multi-level json data, in Mongodb with Python 3.5?
PLAYER_DEFAULT = {
"_id": Inc(PlayersDB),
"mail": "test#gmail.com",
"password": "123456",
"token": uuid4().hex,
"username": "applet",
"user_info":
{
"show_name" : "Hero",
"rate_us": 20000,
"rating": 300,
"gcg": "",
"ration":0,
"items":
[
{"id":1, "item_type":"socket", "name":"aEveA", "data":{"level":1, "stat":"AVA"}},
{"id":2, "item_type":"socket", "name":"aEveA", "data":{"level":4, "stat":"AVA"}},
{"id":3, "item_type":"socket", "name":"Hestos", "data":{"level":9, "stat":"Hest"}},
{"id":4, "item_type":"user", "name":"AAACZX", "data":{"expr":1000}},
{"id":5, "item_type":"user", "name":"AAAAZZZCX", "data": {"expr":1000}}
]
}
}
how get data level and stat in items?
["_id"]->["show_name"]
["_id"]->["user_info"]->["items"]
["_id"]->["user_info"]->["items"] -> get value by "stat" in items[0]
me need get items id, by items "stat" value
i use loop
how get x count?
for x in PlayersDB.find({"_id":1}):
print(x["user_info"]["items"][x.count()])
And... how to update "item_type", by "id", in "items"?
And how to delete 1 docuement by "id":1 in "items"?

For that document, try:
doc['user_info']['items'][0]['data']['stat']
If you have a doc for a player, and want to count how many items that player has, you will use some built-in Python function, which I will call XXX, and which you should research to see what that function is, and use it on the items attribute of the doc:
number_of_items = XXX(doc['user_info']['items'])
And in future, please use the same names and structure in your question as in your posted examples.

Related

How do I get the last element of a json list? [duplicate]

This question already has answers here:
How do I get the last element of a list?
(25 answers)
Closed 1 year ago.
Here I'm trying to get the last m2id to print it into console.
[{
"m2id":"865199733949071370",
"author":{
"id":"862323352869797948"
}
},
{
"m2id":"865199658103078925",
"author":{
"id":"751742911682445312"
}
}]
And here's the code I wrote for it. (r.json being the json above):
data = r.json()
for id in data:
id3 = id["id"][-1]
print(id3)
Running the code gave me the last number of the first m2id, Which is not what I want.
Edit: data[-1]["id"] Worked. Thanks to everyone!
You can try this
x = [{
"m2id":"865199733949071370",
"author":{
"id":"862323352869797948"
}
},
{
"m2id":"865199658103078925",
"author":{
"id":"751742911682445312"
}
}]
print(x[len(x)-1]["m2id"])
Output
865199658103078925

break a line into multilines in JSON [duplicate]

This question already has answers here:
Are multi-line strings allowed in JSON?
(15 answers)
Closed 3 years ago.
I'm trying to read a json file in python and I want to break a long value into multiples lines to make it easier to read it.
e.g JSON file:
mem's value is too long, so I'd like to make it multiple lines.
{
"resource":{
"cpu": ["host, usage_system, usage_user, usage_iowait", "1=1"],
"mem": ["host, active/(1024*1024) as active, available/(1024*1024) as available, available_percent, buffered/(1024*1024) as buffered, cached/(1024*1024) as cached, swap_cached/(1024*1024) swap_cached, swap_total/(1024*1024) swap_total, total/(1024*1024) mem_total, used/(1024*1024) mem_used", "1=1"],
"net": ["host, bytes_recv, bytes_sent, packets_recv, packets_sent", "1=1 and interface != 'all'"]
}
}
I want to make the value like below.
{ "resource":{
"cpu": ["host, usage_system, usage_user, usage_iowait", "1=1"],
"mem": ["host, active/(1024*1024) as active, available/(1024*1024) as available,
available_percent, buffered/(1024*1024) as buffered,
cached/(1024*1024) as cached, swap_cached/(1024*1024) swap_cached,
swap_total/(1024*1024) swap_total,
total/(1024*1024) mem_total, used/(1024*1024) mem_used", "1=1"],
"net": ["host, bytes_recv, bytes_sent, packets_recv, packets_sent", "1=1 and interface != 'all'"]
}
}
Thanks!
ok, so you are probably going to want to make a list of strings in json, then combine them with "".join(). For example,
json.json
{
"multiline": [
"this is a re",
"ally long st",
"ring, so I n",
"eed to make ",
"it one line"
]
}
multiline.py
import json
with open("json.json", "r") as jsonfile:
stringlist = json.loads(jsonfile.read())["multiline"]
result = "".join(stringlist)
print(result)

Trouble when storing API data in Python list

I'm struggling with my json data that I get from an API. I've gone into several api urls to grab my data, and I've stored it in an empty list. I then want to take out all fields that say "reputation" and I'm only interested in that number. See my code here:
import json
import requests
f = requests.get('my_api_url')
if(f.ok):
data = json.loads(f.content)
url_list = [] #the list stores a number of urls that I want to request data from
for items in data:
url_list.append(items['details_url']) #grab the urls that I want to enter
total_url = [] #stores all data from all urls here
for index in range(len(url_list)):
url = requests.get(url_list[index])
if(url.ok):
url_data = json.loads(url.content)
total_url.append(url_data)
print(json.dumps(total_url, indent=2)) #only want to see if it's working
Thus far I'm happy and can enter all urls and get the data. It's in the next step I get trouble. The above code outputs the following json data for me:
[
[
{
"id": 316,
"name": "storabro",
"url": "https://storabro.net",
"customer": true,
"administrator": false,
"reputation": 568
}
],
[
{
"id": 541,
"name": "sega",
"url": "https://wedonthaveanyyet.com",
"customer": true,
"administrator": false,
"reputation": 45
},
{
"id": 90,
"name": "Villa",
"url": "https://brandvillas.co.uk",
"customer": true,
"administrator": false,
"reputation": 6
}
]
]
However, I only want to print out the reputation, and I cannot get it working. If I in my code instead use print(total_url['reputation']) it doesn't work and says "TypeError: list indices must be integers or slices, not str", and if I try:
for s in total_url:
print(s['reputation'])
I get the same TypeError.
Feels like I've tried everything but I can't find any answers on the web that can help me, but I understand I still have a lot to learn and that my error will be obvious to some people here. It seems very similar to other things I've done with Python, but this time I'm stuck. To clarify, I'm expecting an output similar to: [568, 45, 6]
Perhaps I used the wrong way to do this from the beginning and that's why it's not working all the way for me. Started to code with Python in October and it's still very new to me but I want to learn. Thank you all in advance!
It looks like your total_url is a list of lists, so you might write a function like:
def get_reputations(data):
for url in data:
for obj in url:
print(obj.get('reputation'))
get_reputations(total_url)
# output:
# 568
# 45
# 6
If you'd rather not work with a list of lists in the first place, you can extend the list with each result instead of append in the expression used to construct total_url
You can also use json.load and try to read the response
def get_rep():
response = urlopen(api_url)
r = response.read().decode('utf-8')
r_obj = json.loads(r)
for item in r_obj['response']:
print("Reputation: {}".format(item['reputation']))

How to iterate over JSON array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have this JSON array with multiple roots:
[
{
"issuer_ca_id": 16418,
"issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
"name_value": "sub.test.com",
"min_cert_id": 325717795,
"min_entry_timestamp": "2018-02-08T16:47:39.089",
"not_before": "2018-02-08T15:47:39"
},
{
"issuer_ca_id":9324,
"issuer_name":"C=US, O=Amazon, OU=Server CA 1B, CN=Amazon",
"name_value":"marketplace.test.com",
"min_cert_id":921763659,
"min_entry_timestamp":"2018-11-05T19:36:18.593",
"not_before":"2018-10-31T00:00:00",
"not_after":"2019-11-30T12:00:00"
}
]
I want to iterate over it and print issuer_name values in Python. Any solution, please?
Use the json package and load the json. Assuming it is a string in memory (as opposed to a .json file):
jsonstring = """
[
{
"issuer_ca_id": 16418,
"issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
"name_value": "sub.test.com",
"min_cert_id": 325717795,
"min_entry_timestamp": "2018-02-08T16:47:39.089",
"not_before": "2018-02-08T15:47:39"
},
{
"issuer_ca_id":9324,
"issuer_name":"C=US, O=Amazon, OU=Server CA 1B, CN=Amazon",
"name_value":"marketplace.test.com",
"min_cert_id":921763659,
"min_entry_timestamp":"2018-11-05T19:36:18.593",
"not_before":"2018-10-31T00:00:00",
"not_after":"2019-11-30T12:00:00"
}
]"""
import json
j = json.loads(jsonstring)
[item["issuer_name"] for item in j]
Gives:
["C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
'C=US, O=Amazon, OU=Server CA 1B, CN=Amazon']
Now, these don't look like names to me, but that's what is assigned to the issuer_name field, so I think that's something you have to take up with the owner of the data.
If it's a file, you do the loading in this basic pattern:
# something like this
with open("jsonfile.json", "rb") as fp:
j = json.load(fp)
See the docs here: https://docs.python.org/3.7/library/json.html

Python Dictionaries Print [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have this dictionary but I'm not able to print it, could anyone tell me if there is an error?
groseries = {
'fruits':[{
'apples':['7'],
'bananas':['4'],
'lemmons':['7']
}],
'vegestables':[{
'tomatoes':['3'],
'carrots':['9'],
'onions':['6']
}],
'cereals':[{
'wheat':['11'],
'granola':['7'],
'kornflakes':['9']
}]
}
print (groseries['cereals'][2])
groseries['cereals'] has only one element. So using index 2 for it throws the IndexError exception.
Thus the right usage is with the index 0 and the key 'kornflakes':
print(groseries['cereals'][0]['kornflakes'])
Perhaps you meant to format your code like this?:
groceries = {
'fruits': {
'apples':7,
'bananas':4,
'lemons':7
},
'vegetables': {
'tomatoes':3,
'carrots':9,
'onions':6
},
'cereals': {
'wheat':11,
'granola':7,
'cornflakes':9
}
}
So then you can print how many apples you have like this:
print (groceries['fruits']['apples'])
or for cornflakes:
print (groceries['cereals']['cornflakes'])
On a trivial note, shouldn't tomatoes be in fruit? :P
You need groseries['cereals'][0]['kornflakes'].
It's a list of dictionaries (containing only one dictionary) inside groseries['cereals'].
Change your groseries dictionary to
groseries = {
'fruits': {
'apples': 7,
'bananas': 4,
'lemmons': 7
},
'vegestables': {
'tomatoes': 3,
'carrots': 9,
'onions': 6
},
'cereals': {
'wheat': 11,
'granola': 7,
'kornflakes': 9
}
}
(no lists - as all your lists have just 1 item - no numbers in apostrophes, PEP 8 Style Guide's formatting) - and your life will be much easier.
And yes, then you may print the number (or the price?) of your favorite kornflakes cereal as simple as
print(groseries['cereals']['kornflakes'])

Categories