Printing parsed JSON in Python - python

Assuming this is the .JSON file I have to parse:
{
"item": {
"allInventory": {
"onHand": 64,
"total": {
"1000": 0,
"1001": 6,
"1002": 5,
"1003": 3,
"1004": 12,
"1005": 0
}
}
},
"image": {
"tag": "/828402de-6cc8-493e-8abd-935a48a3d766_1.285a6f66ecf3ee434100921a3911ce6c.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF"
}
}
How would I go about printing the total values like:
1000 - 0
1001 - 6
1002 - 5
1003 - 4
1004 - 12
1005 - 0
I have already parsed the values, but I'm unsure of how to actually print them. I've already spent awhile on this and couldn't find a solution so any help is appreciated. Here is my code thus far:
import requests
import json
src = requests.get('https://hastebin.com/raw/nenowimite').json()
stats = src['item']['allInventory']['total']
print(stats)

This can be done through a for loop as follows:
for key in stats.keys():
print(key, '-', stats[key])

Using full Python 3.6 you can do (similarly than Ecir's answer)
for key, value in stats.items():
printf(f'{key} - {value}')
but being clearer about what is the key and the value and using the f-string interpolation.

You are almost there:
for item in stats.items():
print '%d - %d' % item
What this does is that stats is already a dict. Looking at the documentation, there is the items method which returns "a copy of the dictionary’s list of (key, value) pairs". And each pair is formatted as two numbers, i.e. '%d - %d'.

You can try:
>>> import json
>>> data= """{
"item": {
"allInventory": {
"onHand": 64,
"total": {
"1000": 0,
"1001": 6,
"1002": 5,
"1003": 3,
"1004": 12,
"1005": 0
}
}
},
"image": {
"tag": "/828402de-6cc8-493e-8abd-935a48a3d766_1.285a6f66ecf3ee434100921a3911ce6c.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF"
}
}"""
>>> data = json.loads(data)
>>> print data["item"]["allInventory"]["total"]
{'1005': 0, '1004': 12, '1003': 3, '1002': 5, '1001': 6, '1000': 0}

Related

Why doesn't pymongo MongoDB return an exact value in find_one()?

I want to retrieve the single value "count "from pymongo DB but it is not working. The image below shows how the data entry is setup.
Here is the call to my Database class to use the db.find_one().
CODE HERE:
filters = {"email": session.get('email')}
returns = {f'words.{today_s}.{self.length - 3}.count': 1}
count_value = Database.find_one_return_one("users", filters, returns)
print({f'words.{today_s}.{self.length - 3}.count':1})
print(count_value)
#staticmethod
def find_one_return_one(collection: str, query: Dict, data: Dict) -> Dict:
return Database.DATABASE[collection].find_one(query, data)
This returns an empty list of dictionaries from the correct data? I want the count value returned.
This is the projection query: {words.20220302.0.count : 1}
This is what is returned:
{'_id': ObjectId('621ee5065d08c44070140df0'), 'words': {'20220302': [{}, {}, {}, {}, {}, {}, {}]}}
What is wrong or is there a better quicker way to retrieve the count value?
The following query projection can be used to get the desired result. Note this worked with MongoDB v5.
A sample document; similar to the one in the question post:
{ _id: 1, words: { fld: [ { a: 1, b: 2 }, { a: 9, b: 100 } ] } }
The expected result is: { "_id" : 1, "words" : { "fld" : { "a" : 9 } } }
The query:
INDEX = 1 # this is the index of the array element
query = { }
projection = {
'words.fld': {
'$arrayElemAt': [
{ '$map': { 'input': '$words.fld', 'in': { 'a': '$$this.a' } } },
INDEX
]
}
}
result = collection.find_one(query, projection)
print(result)

displaying JSON data more clear in Python [duplicate]

This question already has answers here:
How to prettyprint a JSON file?
(15 answers)
Closed 2 years ago.
I have a json data like
{"Player1": {"inventory": {"tas-count": 5, "kiriktas-count": 0, "odun-count": 0}}}
But it seems too complex. I want to edit, change it like
{
"Player1": {
"inventory": {
"tas-count": 5,
"kiriktas-count": 0,
"odun-count": 0,
}
}
}
I looked for it but there is nothing on Stackoverflow and also things like "\n" are not working. I heard that in other languages, there are libraries for making a clear json data. Might there are some like this in Python.
Here's an example:
>>> import json
>>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
{
"4": 5,
"6": 7
}
You can check out pretty printing here: https://docs.python.org/3/library/json.html
You can try:
import json
data = {"Player1": {"inventory": {"tas-count": 5, "kiriktas-count": 0, "odun-count": 0}}}
print(json.dumps(data, indent=4, sort_keys=True))
Output:
{
"Player1": {
"inventory": {
"kiriktas-count": 0,
"odun-count": 0,
"tas-count": 5
}
}
}

JSON/Python get output from subcategories

New in JSON/Python... I'd like to select a part of sub category.
Here is a part of the JSON file:
{
"items": [{
"seasonId": 59,
"createdDate": "20200721T205735.000Z",
"participants": [{
"tag": "#8CJ89RJ",
"name": "Cåmille",
"cardsEarned": 1401,
"battlesPlayed": 1,
"wins": 1,
"collectionDayBattlesPlayed": 3,
"numberOfBattles": 1
}, {
"tag": "#Y2828CQ",
"name": "<c2>MoutBrout",
"cardsEarned": 1869,
"battlesPlayed": 1,
"wins": 1,
"collectionDayBattlesPlayed": 3,
"numberOfBattles": 1
}, {
"tag": "#2Q8CRC8RY",
"name": "Desnoss",
"cardsEarned": 2337,
"battlesPlayed": 1,
"wins": 0,
"collectionDayBattlesPlayed": 3,
"numberOfBattles": 1
}, {
"tag": "#80CGRR2CY",
"name": "pixtango",
"cardsEarned": 1402,
"battlesPlayed": 1,
"wins": 1,
"collectionDayBattlesPlayed": 2,
"numberOfBattles": 1
}]
}]
}
I would like a result as:
Camille - 1401 cards - 1 win
etc
However, my issue is that those infos are under items/0/participants.
I know how to do with data under one category. Here is an exemple for another JSON file and how I'd like the new one to be:
for item in data ["items"][:5]:
print("Name: %s\nTrophies: %s\nTag: %s\n\n" % (
item["name"],
item["trophies"],
item["tag"],
))
Any idea please ?
EDIT: I'm sorry, here is how it looks:
For exemple, I would like to print the 5 first names. I put this:
for item in data ["items"][:5]:
print (data[items][0][participants]['name'])
And I received this error:
NameError: name 'items' is not defined
maybe you need something like this:
items_str = [f'Name: {i["name"]}\nTrophies: {i["trophies"]}\nTag: "{i["tag"]}'
for i in json_dict['items']]
for i in items_str:
print(i)
sorry, it's not so easy to understand from your data
UPD: If there are many 'items' with 'participants' in each, this code should work for you:
participants = []
for item in json_dict['items']:
for participant in item['participants']:
p = 'Name: {}\nTrophies: {}\nTag: {}'.format(item["name"], item["trophies"], item["tag"])
participants.append(p)
print(p)
sub_dict = dict['items'][0]['participants']
print("Name: {}\nTrophies: {}\nTag:{}\n\n".format(sub_dict['name'],sub_dict['trophies'],sub_dict['tag']))
For other participants increase the array index.
Reading the JSON data from the file and prints it.
import json
with open('j.json','r') as f:
data = json.loads(f.read())
for item in data['items']:
for p in item['participants']:
print p
print("Name: %s\nTrophies: %s\nTag: %s\n\n" % (
p["name"],
p["trophies"],
p["tag"]))
I think it may help you:
Code:
import json
import pandas as pd
j='{"items":[{"seasonId":59,"createdDate":"20200721T205735.000Z","participants":[{"tag":"#8CJ89RJ","name":"Cåmille","cardsEarned":1401,"battlesPlayed":1,"wins":1,"collectionDayBattlesPlayed":3,"numberOfBattles":1},{"tag":"#Y2828CQ","name":"<c2>MoutBrout","cardsEarned":1869,"battlesPlayed":1,"wins":1,"collectionDayBattlesPlayed":3,"numberOfBattles":1},{"tag":"#2Q8CRC8RY","name":"Desnoss","cardsEarned":2337,"battlesPlayed":1,"wins":0,"collectionDayBattlesPlayed":3,"numberOfBattles":1},{"tag":"#80CGRR2CY","name":"pixtango","cardsEarned":1402,"battlesPlayed":1,"wins":1,"collectionDayBattlesPlayed":2,"numberOfBattles":1}]}]}'
y = json.loads(j)
y=pd.DataFrame([x for x in y['items'][0]['participants']])
print(y)
output:

Python sort JSON based on value

I need to sort my JSON based on value in ascending/descending order in PYTHON
This is my JSON:
{
"efg": 1,
"mnp": 4,
"xyz": 3
}
expected output is :
{
"mnp": 4,
"xyz": 3,
"efg": 1,
}
The above is just a sample JSON, Actual JSON is much bigger
And how to reverse sort it based on value
{
"efg": 1,
"xyz": 3,
"mnp": 4
}
Please help
-Ashish
import json
from collections import OrderedDict
json_str = """
{
"efg": 1,
"mnp": 4,
"xyz": 3
}
"""
json_dict = json.loads(json_str)
dict_sorted = OrderedDict(sorted(json_dict.items(), key=lambda x: x[1]))
str_sorted = json.dumps(dict_sorted) # '{"efg": 1, "xyz": 3, "mnp": 4}'

How to get a flat JSON from a nested one?

I have a nested JSON and I need "Max" & "Remaining" percentage values from it.
This is sample formula I am thinking of 100-(Remaining/Max)*100=(Value)
Sample JSON:
{
"ConcurrentAsyncGetReportInstances":
{
"Max": 5,
"Remaining": 3
},
"DailyApiRequests":
{
"Max":15000,"Remaining":14108
}
}
This is the JSON output.
I need to add the % value to the key
Sample output:
{
"ConcurrentAsyncGetReportInstances":40,(%value) 100-(5/3)*100
"DailyApiRequests": 5.95(%value) 100-(14108/15000)*100
}
Workarounds:
Tried to do make it a flat JSON and worked but didn't helped me
Worked on converting JSON into CSV and tried some but it was hard
Can someone suggest the best to do this? If possible provide some examples. Some help would also be appreciated.
Note: I am using Python 2.7
There is now a Python package for this called flatten_json. An introduction is provided here.
An example from that page--
In your shell:
> pip install flatten_json
In your Python console:
from flatten_json import flatten
input_dict = {
"a": 1,
"b": 2,
"c": [{"d": [2, 3, 4], "e": [{"f": 1, "g": 2}]}]
}
print(flatten(input_dict))
Results:
{'a': 1,
'b': 2,
'c_0_d_0': 2,
'c_0_d_1': 3,
'c_0_d_2': 4,
'c_0_e_0_f': 1,
'c_0_e_0_g': 2}
I've tested this in both Python 3.6 and 2.7.
Firstly receive your json and convert it to dictionary
import json
input_dict = json.loads(<your received son string>)
Then work on the input dict like below through recursive calls:
input_dict = {
"ConcurrentAsyncGetReportInstances":
{
"Max": 200,"Remaining":200
},
"DailyApiRequests":
{
"Max": 15000, "Remaining": 14108,
"Ant Migration Tool": {"Max": 0, "Remaining": 0},
"Chatter Desktop": {"Max": 0, "Remaining": 0},
"Chatter Mobile for BlackBerry":
{"Max": 0, "Remaining": 0},
"Chemical Equipment And Processing":
{"Max": 0,"Remaining": 0}
}
}
def flattenjson(input_dict, odict):
for ky in input_dict.keys():
if isinstance(input_dict[ky], dict):
if set(['Max', 'Remaining']).issubset(input_dict[ky].keys()):
if input_dict[ky]["Max"] != 0:
odict[ky] = 100-(float(input_dict[ky]["Remaining"])/input_dict[ky]["Max"])*100
else:
odict[ky] = 0
for iky in input_dict[ky].keys():
if isinstance(input_dict[ky][iky], dict):
tmp = {iky : input_dict[ky][iky]}
odict = flattenjson(tmp, odict)
return odict
odict = flattenjson(input_dict, dict())
print json.dumps(odict)
flattenjson helps you recursively work on to get your desired output for all Max and Remaining entries
You can retrieve nested values using the json library like so:
import json
sample_json = '{"ConcurrentAsyncGetReportInstances":{"Max": 5,"Remaining": 3},"DailyApiRequests": {"Max":15000,"Remaining":14108}}'
jason = json.loads(sample_json)
cagri_max = jason['ConcurrentAsyncGetReportInstances']['Max']
cagri_rem = jason['ConcurrentAsyncGetReportInstances']['Remaining']
You don't need to flatten the data structure. Just reference that pieces of it you want—so, for example, I think the following does essentially what you want:
import json
json_data = {
"ConcurrentAsyncGetReportInstances": {
"Max": 5,
"Remaining": 3
},
"DailyApiRequests": {
"Max": 15000,
"Remaining": 14108
}
}
def percentage_values(remaining, maximum):
return 100 - (float(remaining)/float(maximum)) * 100
# build output dictionary
json_out = {}
for key in json_data:
value = percentage_values(json_data[key]["Remaining"], json_data[key]["Max"])
json_out.update([(key, value)])
print(json.dumps(json_out, indent=4))
The resulting output showing the contents of json_out is:
{
"ConcurrentAsyncGetReportInstances": 40.0,
"DailyApiRequests": 5.9466666666666725
}
There are more succinct ways to write this in Python, but they all would do what is done above in a very simple manner.

Categories

Resources