JSON/Python get output from subcategories - python

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:

Related

python sort over list by value Json sctructure

I'm trying to get an output of a json file sorted by the following value "created_at"
there a bit mass regarding all my tries in the code, I wasn't able to sort it.
If there is better solutions to resolve this task you more then welcome to share.
Your help and patience is much appreciated
import json
from datetime import datetime
import operator
from collections import OrderedDict
from operator import itemgetter
null = None
true = True
false = False
text = {
"Recipes":
[
{
"id": 2090210,
"user_id": 198555,
"parent_id": null,
"folder_id": 792876,
"version_no": 17,
"last_run_at": "2022-01-13T03:52:31.559455-08:00",
"created_at": "2022-01-13T00:53:48.433452-08:00",
"updated_at": "2022-01-13T03:52:27.798961-08:00",
"job_succeeded_count": 7,
"job_failed_count": 0,
"lifetime_task_count": 209,
"active": true
},
{
"id": 2072031,
"user_id": 198555,
"parent_id": null,
"folder_id": 283206,
"version_no": 98,
"last_run_at": "2022-01-04T05:14:41.485273-08:00",
"created_at": "2022-01-14T05:12:56.677338-08:00",
"updated_at": "2022-01-12T10:08:49.199488-08:00",
"job_succeeded_count": 1,
"job_failed_count": 0,
"lifetime_task_count": 227,
"active": false
},
]
}
#info = json.dump(text, sort_keys=False)
sorted_values = sorted(text.values())
#text.sort(key=lambda s: s['created_at'])
sorted_d = {r: text[r] for r in sorted(text, key=text.get('created_at'), reverse=True)}
#print(sorted_d)
ss = sorted(text.values()) #no recips
#print(ss)
newlist = sorted(ss, key=itemgetter(1))
print(newlist)
No need to write extra lines just write this one line and it will sort you data
sorted_text = { "Recipes" : sorted(text['Recipes'], key=itemgetter('created_at'))}
print(sorted_text)

json with array

I am trying to create a dict like this:
{
"Name": "string",
"Info": [
{
"MainID": "00000000-0000-0000-0000-000000000000",
"Values": [
{
"IndvidualID": "00000000-0000-0000-0000-000000000000",
"Result": "string"
},
{
"IndvidualID": "00000000-0000-0000-0000-000000000000",
"Result": "string"
}
]
}
]
}
Where the Values section has 100+ things inside of it. I put 2 as an example.
Unsure how to build this dynamically. Code I have attempted so far:
count = 0
with open('myTextFile.txt') as f:
line = f.readline()
line = line.rstrip()
myValues[count]["IndvidualID"] = count
myValues[count]["Result"] = line
count = count +1
data = {"Name": "Demo",
"Info": [{
"MainID":TEST_SUITE_ID,
"Values":myValues
}}
This does not work however. Due to "Key Error 0" it says. Works if I do it like myValues[count]= count but as soon as I add the extra layer it breaks myValues[count]["IndvidualID"] = count. I see some example of setting a list in there, but I need like a List (Values) with multiple things inside (ID and Result). Have tried a few things with no luck. Anyone have a simple way to do this in python?
Full traceback:
Traceback (most recent call last):
File "testExtractor.py", line 28, in <module>
myValues[count]["IndvidualID"] = count
KeyError: 0
If I add a few bits and pieces I can get this code to run:
count = 0
myValues = []
with open('myTextFile.txt') as f:
for line in f:
line = line.rstrip()
d = {"IndvidualID":count, "Result":line}
myValues.append(d)
count = count + 1
TEST_SUITE_ID = 1
data = {"Name": "Demo",
"Info": [{
"MainID":TEST_SUITE_ID,
"Values":myValues
}]}
Output:
{'Name': 'Demo', 'Info': [{'MainID': 1,
'Values': [{'IndvidualID': 0, 'Result': 'apples'}, {'IndvidualID': 1, 'Result': 'another apples'}]
}]}
Note:
I have defined myValues as an empty list. I iterate over the file to read all lines and I create a new dict for each line, appending to myValues each time. Finally I create the whole data object with myValues embedded inside.
To get the above output I actually substituted: f = ['apples','another apples'] for the open file, but I'm sure an actual file would work.

How to loop through a JSON file using Python with nested lists and dictionaries

I'm trying to loop through a JSON file using Python and return the name of the object and associated modules for it.
Right now I can basically get the output I want hardcoding the indexes. However, this obviously isn't the right way to do it (the JSON file can vary in length).
Whenever I try to use a loop, I get errors like:
TypeError: string indices must be integers
My JSON file looks like this:
{
"name": "gaming_companies",
"columns": [{
"name": "publisher",
"type": "string",
"cleansing": ["clean_string"]
},
{
"name": "genre",
"type": "string",
"cleansing": ["match_genre", "clean_string"]
},
{
"name": "sales",
"type": "int",
"cleansing": []
}
]
}
My Python code which is 'working' looks like:
import json as js
def cleansing(games_json):
print (games_json['columns'][0]['name'] + " - cleansing:")
[print(i) for i in games_json['columns'][0]['cleansing'] ]
print (games_json['columns'][1]['name'] + " - cleansing:")
[print(i) for i in games_json['columns'][1]['cleansing'] ]
print (games_json['columns'][2]['name'] + " - cleansing:")
[print(i) for i in games_json['columns'][2]['cleansing'] ]
with open(r'C:\Desktop\gamefolder\jsonfiles\games.json') as input_json:
games_json = js.load(input_json)
cleansing(games_json)
The output I'm trying to return is:
publisher
cleansing:
clean_string
genre
cleansing:
match_genre
clean_string
sales
cleansing:
My attempt to loop through them like this:
for x in games_json:
for y in games_json['columns'][x]:
print (y)
Results in:
TypeError: list indices must be integers or slices, not str
games_json shows as a Dict.
Columns shows as a list of dictionaries.
Each object's cleansing attribute shows as a list.
I think this is where my problem is, but I'm not able to get over the hurdle.
The problem with your attempt is using an iterator as a string.
The x in for y in games_json['columns'][x]: is an iterator object and not the strings ['name', 'cleansing'].
You can learn more about python iterators here
As for the case - you might want to iterate over the columns as a separate list.
This code should work
for item in f["columns"]:
print(item["name"])
print("cleansing:")
print(item["cleansing"])
Output-
publisher
cleansing:
['clean_string']
genre
cleansing:
['match_genre', 'clean_string']
sales
cleansing:
[]
This can be one of working solutions as you want to iterate array's elements.
import json
for x in games_json['columns']:
print(x)
print(x['name'])
x = """{
"name": "gaming_companies",
"columns": [{
"name": "publisher",
"type": "string",
"cleansing": ["clean_string"]
},
{
"name": "genre",
"type": "string",
"cleansing": ["match_genre", "clean_string"]
},
{
"name": "sales",
"type": "int",
"cleansing": []
}
]
}"""
x = json.loads(x)
for i in x['columns']:
print(i['name'])
print("cleansing:")
for j in i["cleansing"]:
print(j)
print('\n')
Output
publisher
cleansing:
clean_string
genre
cleansing:
match_genre
clean_string
sales
cleansing:
with open(r'C:\Desktop\gamefolder\jsonfiles\games.json') as input_json:
games_json = js.load(input_json)
for i in games_json['columns']:
print(i['name'])
print("cleansing:")
for j in i["cleansing"]:
print(j)
print('\n')

Printing parsed JSON in 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}

How to take the first two letters of a variable in python?

I have a dataset like below:
data
id message
1 ffjffjf
2 ddjbgg
3 vvnvvv
4 eevvff
5 ggvfgg
Expected output:
data
id message splitmessage
1 ffjffjf ff
2 ddjbgg dd
3 vvnvvv vv
4 eevvff ee
5 ggvfgg gg
I am very new to Python. So how can I take 1st two letters from each row in splitmessage variable.
my data exactly looks like below image
so from the image i want only hour and min's which are 12 to 16 elements in each row of vfreceiveddate variable.
dataset = [
{ "id": 1, "message": "ffjffjf" },
{ "id": 2, "message": "ddjbgg" },
{ "id": 3, "message": "vvnvvv" },
{ "id": 4, "message": "eevvff" },
{ "id": 5, "message": "ggvfgg" }
]
for d in dataset:
d["splitmessage"] = d["message"][:2]
What you want is a substring.
mystr = str(id1)
splitmessage = mystr[:2]
Method we are using is called slicing in python, works for more than strings.
In next example 'message' and 'splitmessage' are lists.
message = ['ffjffjf', 'ddjbgg']
splitmessage = []
for myString in message:
splitmessage.append(myString[:2])
print splitmessage
If you want to do it for the entire table, I would do it like this:
dataset = [id1, id2, id3 ... ]
for id in dataset:
splitid = id[:2]

Categories

Resources