I am new to Python and JSON. I am calling an API and as response body I am getting below :
{'product': 'Cycle', 'available': 20, 'blocked': 0, 'orderBooked': 0, 'transfer': 0, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '2000112', 'locationId': '745', 'locationCode': '425', 'stockType': 'IN STOCK', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0}
{'product': 'Cooker', 'available': 958, 'blocked': 10, 'orderBooked': 10, 'transfer': 30, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '589620', 'locationId': '420', 'locationCode': '695', 'stockType': 'PRE ORDER', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0}
{'product': 'Cycle', 'available': 96220, 'blocked': 0, 'orderBooked': 0, 'transfer': 0, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '2000112', 'locationId': '745', 'locationCode': '425', 'stockType': 'CONFIRMED', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0}
{'product': 'Lapms', 'available': 89958, 'blocked': 1890, 'orderBooked': 1045, 'transfer': 230, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '78963', 'locationId': '896', 'locationCode': '463', 'stockType': 'TRANSIT', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0}
The data I mentioned above will vary as per the API request. So Whatever be the response. Based on the Products, I need to Print Multi line data. My request is to read this Json and get the following Data :
Name:<'product'>, Code:<'lCode'>, Location:<'locationCode'>, Stock Type:<'stockType'>, Availability:<'available'>
So For the Above Json, the output should be like :
Name:Cycle, Code:2000112, Location:425, Stock Type:PRE ORDER, Availability:20
Name:Cooker, Code:589620, Location:695, Stock Type:<'stockType'>, Availability:958
Name:Cycle, Code:2000112, Location:425, Stock Type:CONFIRMED, Availability:96220
Name:Lapms, Code:78963, Location:463, Stock Type:TRANSIT, Availability:89958
So Based on the Times,
product is occuring, the data output will be having that much lines
I dont have any idea on parsing Json in Python. Please help in understanding how I can get the data in below format. I havent tried anything as I am stuck
This is what I believe you want. As some comments say, indeed these outputs should be treated as dictionaries or lists, with dictionaries and/or lists nested within them. It's important to know the difference since the first should be addressed by its key whereas the latter by its index. You can find some extra information regarding how to read jsons/dictionaries here
import pandas as pd
json_1 = {'product': 'Cycle', 'available': 20, 'blocked': 0, 'orderBooked': 0, 'transfer': 0, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '2000112', 'locationId': '745', 'locationCode': '425', 'stockType': 'IN STOCK', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0}
json_2 = {'product': 'Cooker', 'available': 958, 'blocked': 10, 'orderBooked': 10, 'transfer': 30, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '589620', 'locationId': '420', 'locationCode': '695', 'stockType': 'PRE ORDER', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0}
json_3 = {'product': 'Cycle', 'available': 96220, 'blocked': 0, 'orderBooked': 0, 'transfer': 0, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '2000112', 'locationId': '745', 'locationCode': '425', 'stockType': 'CONFIRMED', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0}
json_4 = {'product': 'Lapms', 'available': 89958, 'blocked': 1890, 'orderBooked': 1045, 'transfer': 230, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '78963', 'locationId': '896', 'locationCode': '463', 'stockType': 'TRANSIT', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0}
support_list = []
support_list.append([json_1,json_2,json_3,json_4])
support_dict = {'Name':[],'Code':[],'Location':[],'Stock type':[],'Availability':[]}
for i in range(len(support_list[0])):
support_dict['Name'].append(support_list[0][i]['product'])
support_dict['Code'].append(support_list[0][i]['lCode'])
support_dict['Location'].append(support_list[0][i]['locationCode'])
support_dict['Stock type'].append(support_list[0][i]['stockType'])
support_dict['Availability'].append(support_list[0][i]['available'])
df = pd.DataFrame(support_dict)
print(df)
Output:
Name Code Location Stock type Availability
0 Cycle 2000112 425 IN STOCK 20
1 Cooker 589620 695 PRE ORDER 958
2 Cycle 2000112 425 CONFIRMED 96220
3 Lapms 78963 463 TRANSIT 89958
EDIT: OPs says it's only list with multiple jsons in it.
It applies the same logic:
import pandas as pd
json_output= [{'product': 'Cycle', 'available': 20, 'blocked': 0, 'orderBooked': 0, 'transfer': 0, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '2000112', 'locationId': '745', 'locationCode': '425', 'stockType': 'IN STOCK', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0},{'product': 'Cooker', 'available': 958, 'blocked': 10, 'orderBooked': 10, 'transfer': 30, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '589620', 'locationId': '420', 'locationCode': '695', 'stockType': 'PRE ORDER', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0},{'product': 'Cycle', 'available': 96220, 'blocked': 0, 'orderBooked': 0, 'transfer': 0, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '2000112', 'locationId': '745', 'locationCode': '425', 'stockType': 'CONFIRMED', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0},{'product': 'Lapms', 'available': 89958, 'blocked': 1890, 'orderBooked': 1045, 'transfer': 230, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '78963', 'locationId': '896', 'locationCode': '463', 'stockType': 'TRANSIT', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0}]
support_dict = {'Name':[],'Code':[],'Location':[],'Stock type':[],'Availability':[]}
for i in range(len(json_output)):
support_dict['Name'].append(json_output[i]['product'])
support_dict['Code'].append(json_output[i]['lCode'])
support_dict['Location'].append(json_output[i]['locationCode'])
support_dict['Stock type'].append(json_output[i]['stockType'])
support_dict['Availability'].append(json_output[i]['available'])
df = pd.DataFrame(support_dict)
print(df)
Output:
Name Code Location Stock type Availability
0 Cycle 2000112 425 IN STOCK 20
1 Cooker 589620 695 PRE ORDER 958
2 Cycle 2000112 425 CONFIRMED 96220
3 Lapms 78963 463 TRANSIT 89958
EDIT 2: If you want the output as lines:
json_output= [{'product': 'Cycle', 'available': 20, 'blocked': 0, 'orderBooked': 0, 'transfer': 0, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '2000112', 'locationId': '745', 'locationCode': '425', 'stockType': 'IN STOCK', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0},{'product': 'Cooker', 'available': 958, 'blocked': 10, 'orderBooked': 10, 'transfer': 30, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '589620', 'locationId': '420', 'locationCode': '695', 'stockType': 'PRE ORDER', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0},{'product': 'Cycle', 'available': 96220, 'blocked': 0, 'orderBooked': 0, 'transfer': 0, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '2000112', 'locationId': '745', 'locationCode': '425', 'stockType': 'CONFIRMED', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0},{'product': 'Lapms', 'available': 89958, 'blocked': 1890, 'orderBooked': 1045, 'transfer': 230, 'restock': 0, 'unavailable': 0, 'total': 0, 'lCode': '78963', 'locationId': '896', 'locationCode': '463', 'stockType': 'TRANSIT', 'adminStock': {'rp': 0, 'management': 0, 'rc': 0, 'total': 0, 'default': 0}, 'isBlocked': False, 'plannedDate': None, 'plannedUpdate': True, 'bookedQuantity': 0}]
for i in range(len(json_output)):
print('Name: ' + str(json_output[i]['product']) + ', Code: ' + str(json_output[i]['lCode']) + ', Location: ' + str(json_output[i]['locationCode']) + ', Stock type: ' + str(json_output[i]['stockType']) + ', Availability: ' + str(json_output[i]['available']))
Output:
Name: Cycle, Code: 2000112, Location: 425, Stock type: IN STOCK, Availability: 20
Name: Cooker, Code: 589620, Location: 695, Stock type: PRE ORDER, Availability: 958
Name: Cycle, Code: 2000112, Location: 425, Stock type: CONFIRMED, Availability: 96220
Name: Lapms, Code: 78963, Location: 463, Stock type: TRANSIT, Availability: 89958
If you parse json file you will get standard python dictionary.
import json
json_data = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}'
parsed_json = (json.loads(json_data))
Related
I have JSON file containing something like this.
[7500,
'29-Dec-2022',
{'strikePrice': 7500, 'expiryDate': '29-Dec-2022', 'underlying': 'NIFTY', 'identifier': 'OPTIDXNIFTY29-12-2022PE7500.00', 'openInterest': 21, 'changeinOpenInterest': 0, 'pchangeinOpenInterest': 0, 'totalTradedVolume': 0, 'impliedVolatility': 0, 'lastPrice': 8.6, 'change': 0, 'pChange': 0, 'totalBuyQuantity': 1800, 'totalSellQuantity': 0, 'bidQty': 1800, 'bidprice': 3.05, 'askQty': 0, 'askPrice': 0, 'underlyingValue': 17287.05},
8300,
'30-Jun-2022',
{'strikePrice': 8300, 'expiryDate': '30-Jun-2022', 'underlying': 'NIFTY', 'identifier': 'OPTIDXNIFTY30-06-2022PE8300.00', 'openInterest': 3, 'changeinOpenInterest': 0, 'pchangeinOpenInterest': 0, 'totalTradedVolume': 0, 'impliedVolatility': 0, 'lastPrice': 4.7, 'change': 0, 'pChange': 0, 'totalBuyQuantity': 1050, 'totalSellQuantity': 0, 'bidQty': 750, 'bidprice': 0.35, 'askQty': 0, 'askPrice': 0, 'underlyingValue': 17287.05},
8500,
'29-Jun-2023', {'strikePrice': 8500, 'expiryDate': '29-Jun-2023', 'underlying': 'NIFTY', 'identifier': 'OPTIDXNIFTY29-06-2023CE8500.00', 'openInterest': 319.5, 'changeinOpenInterest': 0, 'pchangeinOpenInterest': 0, 'totalTradedVolume': 0, 'impliedVolatility': 0, 'lastPrice': 1775, 'change': 0, 'pChange': 0, 'totalBuyQuantity': 0, 'totalSellQuantity': 50, 'bidQty': 0, 'bidprice': 0, 'askQty': 50, 'askPrice': 9970, 'underlyingValue': 17287.05},
8500,
'29-Dec-2022',
{'strikePrice': 8500, 'expiryDate': '29-Dec-2022', 'underlying': 'NIFTY', 'identifier': 'OPTIDXNIFTY29-12-2022PE8500.00', 'openInterest': 2254, 'changeinOpenInterest': 0, 'pchangeinOpenInterest': 0, 'totalTradedVolume': 0, 'impliedVolatility': 0, 'lastPrice': 22.9, 'change': 0, 'pChange': 0, 'totalBuyQuantity': 2700, 'totalSellQuantity': 0, 'bidQty': 1800, 'bidprice': 3.15, 'askQty': 0, 'askPrice': 0, 'underlyingValue': 17287.05}]
Code:
read_cont = []
new_list1 = []
new_list2 = []
for i in rjson:
for j in rjson[i]:
read_cont.append(rjson[i][j])
data_filter = read_cont[1]
for item in data_filter:
for j in item:
new_list1.append(item[j])
new_list1 = map(str,new_list1)
for i in new_list1:
if len(i) > 100:
new_list2.append(i)
header_names = ["STRIKE PRICE","EXPIRY","underlying", "identifier","OPENINTEREST","changeinOpenInterest","pchangeinOpenInterest", "totalTradedVolume","impliedVolatility","lastPrice","change","pChange", "totalBuyQuantity","totalSellQuantity","bidQty","bidprice","askQty","askPrice","underlyingValue"]
df = pd.DataFrame(columns=header_names)
In order to separate the strikePrice entries from the nested list, I had converted all the items to string
["{'strikePrice': 7500, 'expiryDate': '29-Dec-2022', 'underlying': 'NIFTY', 'identifier': 'OPTIDXNIFTY29-12-2022PE7500.00', 'openInterest': 21, 'changeinOpenInterest': 0, 'pchangeinOpenInterest': 0, 'totalTradedVolume': 0, 'impliedVolatility': 0, 'lastPrice': 8.6, 'change': 0, 'pChange': 0, 'totalBuyQuantity': 1800, 'totalSellQuantity': 0, 'bidQty': 1800, 'bidprice': 3.05, 'askQty': 0, 'askPrice': 0, 'underlyingValue': 17287.05}",
"{'strikePrice': 8300, 'expiryDate': '30-Jun-2022', 'underlying': 'NIFTY', 'identifier': 'OPTIDXNIFTY30-06-2022PE8300.00', 'openInterest': 3, 'changeinOpenInterest': 0, 'pchangeinOpenInterest': 0, 'totalTradedVolume': 0, 'impliedVolatility': 0, 'lastPrice': 4.7, 'change': 0, 'pChange': 0, 'totalBuyQuantity': 1050, 'totalSellQuantity': 0, 'bidQty': 750, 'bidprice': 0.35, 'askQty': 0, 'askPrice': 0, 'underlyingValue': 17287.05}"
Now I want to transfer the content to a data frame containing the below column mention in the code
result_dict = []
result_values = []
for i in range(2, len(input_list), 3):
result_dict.append(input_list[i])
result_values.append(input_list[i].values())
col_names = list(result_dict[0].keys())
result_df = pd.DataFrame(result_values, columns = col_names)
rjson = response.json()
read_cont = []
new_list1 = []
new_list2 = []
for i in rjson:
for j in rjson[i]:
read_cont.append(rjson[i][j])
data_filter = read_cont[1]
for item in data_filter:
for j in item:
new_list1.append(item[j])
for j in new_list1:
if type(j) == dict:
new_list2.append(j)
df = pd.DataFrame(new_list2)
Similar questions have already been asked, but I could not find the result I'm looking for.
I have two lists of dictionaries:
[{'name': 'Vijver', 'room': 255, 'module_type': 'O', 'id': 0},{'name': 'Boom', 'room': 255, 'module_type': 'O', 'id': 1}]
[{'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 0, 'locked': False},{'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 1, 'locked': False}]
The 'id' is the same in both dictionaries. I'm not sure if the lists are ordered.
I would like to merge them with the following result:
[{'name': 'Vijver', 'room': 255, 'module_type': 'O', 'id': 0, 'status': {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 0, 'locked': False}},{'name': 'Boom', 'room': 255, 'module_type': 'O', 'id': 1, 'status': {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 1, 'locked': False}}]
How can this be done in Python (3.9+)? Pandas is too heavy, preferably something more light.
That's quite simple, you just need to iterate through the two lists and add a key to the dictionary with the value of the 'inner' dictionary.
list_dict = [
{'name': 'Vijver', 'room': 255, 'module_type': 'O', 'id': 0},
{'name': 'Boom', 'room': 255, 'module_type': 'O', 'id': 1}
]
status_list = [
{'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 0, 'locked': False},
{'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 1, 'locked': False}
]
for idx in range(len(list_dict)):
list_dict[idx]["status"] = status_list[idx]
desired_dict_list = [
{
'name': 'Vijver',
'room': 255,
'module_type': 'O',
'id': 0,
'status': {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 0, 'locked': False}
},
{
'name': 'Boom',
'room': 255,
'module_type': 'O',
'id': 1,
'status': {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 1, 'locked': False}
}
]
for idx in range(len(desired_dict_list)):
if list_dict[idx] != desired_dict_list[idx]:
raise ValueError("Not valid dictionary!")
print(f"Valid dictionary: {list_dict}")
Output:
Valid dictionary: [{'name': 'Vijver', 'room': 255, 'module_type': 'O', 'id': 0, 'status': {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 0, 'locked': False}}, {'name': 'Boom', 'room': 255, 'module_type': 'O', 'id': 1, 'status': {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 1, 'locked': False}}]
You only need the code till the first for-loop, the code after the definition of desired_dict_list is just to validate the concept.
You can use dictionary comprehension in order to produce for each list a dictionary that maps ids to corresponding entries, and then use those dictionaries to combine them.
For instance:
l = [{'name': 'Vijver', 'room': 255, 'module_type': 'O', 'id': 0},{'name': 'Boom', 'room': 255, 'module_type': 'O', 'id': 1}]
d = {elem["id"] : elem for elem in l}
If using python 3.9+ you can use | to merge dictionaries:
l1 = [{'name': 'Vijver', 'room': 255, 'module_type': 'O', 'id': 0}, {'name': 'Boom', 'room': 255, 'module_type': 'O', 'id': 1}]
print(f'{l1 = }')
l2 = [{'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 0, 'locked': False}, {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 1, 'locked': False}]
print(f'{l2 = }')
l3 = [d1 | {'status': d2} for d1, d2 in zip(l1, l2)]
print(f'{l3 = }')
expected = [{'name': 'Vijver', 'room': 255, 'module_type': 'O', 'id': 0, 'status': {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 0, 'locked': False}}, {'name': 'Boom', 'room': 255, 'module_type': 'O', 'id': 1, 'status': {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 1, 'locked': False}}]
print(f'{expected = }')
print(f'{expected == l3 = }')
Output:
l1 = [{'name': 'Vijver', 'room': 255, 'module_type': 'O', 'id': 0}, {'name': 'Boom', 'room': 255, 'module_type': 'O', 'id': 1}]
l2 = [{'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 0, 'locked': False}, {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 1, 'locked': False}]
l3 = [{'name': 'Vijver', 'room': 255, 'module_type': 'O', 'id': 0, 'status': {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 0, 'locked': False}}, {'name': 'Boom', 'room': 255, 'module_type': 'O', 'id': 1, 'status': {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 1, 'locked': False}}]
expected = [{'name': 'Vijver', 'room': 255, 'module_type': 'O', 'id': 0, 'status': {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 0, 'locked': False}}, {'name': 'Boom', 'room': 255, 'module_type': 'O', 'id': 1, 'status': {'status': 0, 'dimmer': 100, 'ctimer': 0, 'id': 1, 'locked': False}}]
expected == l3 = True
I am trying to print out the price of an item from this page/JSON:
https://shopee.sg/api/v2/item/get?itemid=2590867516&shopid=165420215
but I am encountering an error as below:
print([d.get('price_max_before_discount') for d in site_json['item'] if d.get('price_max_before_discount')])
AttributeError: 'str' object has no attribute 'get'
import json
from urllib import request
from bs4 import BeautifulSoup
url = 'https://shopee.sg/api/v2/item/get?itemid=2590867516&shopid=165420215'
html = request.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
site_json = json.loads(soup.text)
print([d.get('price_max_before_discount') for d in site_json['item'] if d.get('price_max_before_discount')])
not sure what I am doing wrong but I will appreciate any advice/solutions!
Thank you.
The API url is returning the json object and you can simply use:
import json
from urllib import request
url = 'https://shopee.sg/api/v2/item/get?itemid=2590867516&shopid=165420215'
data = request.urlopen(url).read()
data_json = json.loads(data)
print(data_json)
Output:
{'item': {'itemid': 2590867516, 'price_max_before_discount': 54900000, 'item_status': 'normal', 'can_use_wholesale': False, 'show_free_shipping': True, 'estimated_days': 2, 'is_hot_sales': None, 'is_slash_price_item': False, 'upcoming_flash_sale': None, 'slash_lowest_price': None, 'is_partial_fulfilled': False, 'condition': 1, 'show_original_guarantee': True, 'add_on_deal_info': None, 'is_non_cc_installment_payment_eligible': False, 'categories': [{'display_name': 'Mobile & Gadgets', 'catid': 8, 'image': None, 'no_sub': False, 'is_default_subcat': False, 'block_buyer_platform': None}, {'display_name': 'Mobile Phones & Tablets', 'catid': 10941, 'image': None, 'no_sub': False, 'is_default_subcat': False, 'block_buyer_platform': None}, {'display_name': 'Samsung', 'catid': 10944, 'image': None, 'no_sub': True, 'is_default_subcat': False, 'block_buyer_platform': None}], 'ctime': 1564663070, 'name': "(New Launch) Samsung Galaxy Tab S6 Lite 10.4' LTE Version with S Pen 64GB", 'show_shopee_verified_label': False, 'size_chart': None, 'is_pre_order': False, 'service_by_shopee_flag': None, 'historical_sold': 186, 'reference_item_id': '', 'recommendation_info': None, 'bundle_deal_info': None, 'price_max': 46500000, 'has_lowest_price_guarantee': False, 'shipping_icon_type': 0, 'images': ['68ce24874257ec3c593d0d118e9cf785'], 'price_before_discount': 54900000, 'cod_flag': 0, 'catid': 8, 'is_official_shop': False, 'coin_earn_label': None, 'hashtag_list': None, 'sold': 62, 'makeup': None, 'item_rating': {'rating_star': 4.976744, 'rating_count': [88, 0, 2, 0, 2, 84], 'rcount_with_image': 40, 'rcount_with_context': 58}, 'show_official_shop_label_in_title': False, 'discount': '15%', 'reason': None, 'label_ids': [1000012, 1000035, 1000088, 1001261], 'has_group_buy_stock': False, 'other_stock': 0, 'deep_discount': None, 'attributes': [{'is_pending_qc': False, 'idx': 0, 'value': 'Samsung', 'id': 10054, 'is_timestamp': False, 'name': 'Brand'}, {'is_pending_qc': False, 'idx': 1, 'value': 'Galaxy Tab S6', 'id': 10093, 'is_timestamp': False, 'name': 'Model'}, {'is_pending_qc': True, 'idx': 2, 'value': '64GB', 'id': 10091, 'is_timestamp': False, 'name': 'Built-in Storage'}, {'is_pending_qc': True, 'idx': 3, 'value': '', 'id': 10094, 'is_timestamp': False, 'name': 'RAM'}, {'is_pending_qc': True, 'idx': 4, 'value': '1 Month', 'id': 10095, 'is_timestamp': False, 'name': 'Warranty Period'}], 'badge_icon_type': 0, 'liked': False, 'cmt_count': 88, 'image': '68ce24874257ec3c593d0d118e9cf785', 'recommendation_algorithm': None, 'is_cc_installment_payment_eligible': True, 'shopid': 165420215, 'normal_stock': 8, 'video_info_list': [], 'installment_plans': [{'banks': [{'bank_name': 'UOB', 'sub_options': [{'disabled_reason': None, 'data': {'bank_name': 'UOB', 'down_payment': 0, 'name': '6x # 0%', 'interest_rate': 0, 'option_id': None, 'bank_id': 1641, 'installment_amount': 46500000, 'channel_id': 1000501, 'monthly_installment': 7750000, 'tenure': 6, 'total_amount': 46500000}, 'name': 'Airpay CC Installment [label_bank_uob #6x]', 'option_info': '1000501-19005014'}, {'disabled_reason': None, 'data': {'bank_name': 'UOB', 'down_payment': 0, 'name': '12x # 0%', 'interest_rate': 0, 'option_id': None, 'bank_id': 1641, 'installment_amount': 46500000, 'channel_id': 1000501, 'monthly_installment': 3875000, 'tenure': 12, 'total_amount': 46500000}, 'name': 'Airpay CC Installment [label_bank_uob #12x]', 'option_info': '1000501-19005015'}], 'bank_id': 1641, 'bank_logo': 'https://mall.shopee.sg/static/images/bank_logo/ic_bank_uob.png'}, {'bank_name': 'DBS/POSB', 'sub_options': [{'disabled_reason': None, 'data': {'bank_name': 'DBS/POSB', 'down_payment': 0, 'name': '6x # 0%', 'interest_rate': 0, 'option_id': None, 'bank_id': 4, 'installment_amount': 46500000, 'channel_id': 1000501, 'monthly_installment': 7750000, 'tenure': 6, 'total_amount': 46500000}, 'name': 'Airpay CC Installment [label_bank_dbs_posb #6x]', 'option_info': '1000501-19005011'}, {'disabled_reason': None, 'data': {'bank_name': 'DBS/POSB', 'down_payment': 0, 'name': '12x # 0%', 'interest_rate': 0, 'option_id': None, 'bank_id': 4, 'installment_amount': 46500000, 'channel_id': 1000501, 'monthly_installment': 3875000, 'tenure': 12, 'total_amount': 46500000}, 'name': 'Airpay CC Installment [label_bank_dbs_posb #12x]', 'option_info': '1000501-19005012'}], 'bank_id': 4, 'bank_logo': 'https://mall.shopee.sg/static/images/bank_logo/ic_bank_dbs.png'}, {'bank_name': 'AMERICAN EXPRESS', 'sub_options': [{'disabled_reason': None, 'data': {'bank_name': 'AMERICAN EXPRESS', 'down_payment': 0, 'name': '6x # 0%', 'interest_rate': 0, 'option_id': None, 'bank_id': 437, 'installment_amount': 46500000, 'channel_id': 1000501, 'monthly_installment': 7750000, 'tenure': 6, 'total_amount': 46500000}, 'name': 'Airpay CC Installment [AMERICAN EXPRESS #6x]', 'option_info': '1000501-19005020'}, {'disabled_reason': None, 'data': {'bank_name': 'AMERICAN EXPRESS', 'down_payment': 0, 'name': '12x # 0%', 'interest_rate': 0, 'option_id': None, 'bank_id': 437, 'installment_amount': 46500000, 'channel_id': 1000501, 'monthly_installment': 3875000, 'tenure': 12, 'total_amount': 46500000}, 'name': 'Airpay CC Installment [AMERICAN EXPRESS #12x]', 'option_info': '1000501-19005021'}], 'bank_id': 437, 'bank_logo': ''}, {'bank_name': 'OCBC', 'sub_options': [{'disabled_reason': None, 'data': {'bank_name': 'OCBC', 'down_payment': 0, 'name': '6x # 0%', 'interest_rate': 0, 'option_id': None, 'bank_id': 3430, 'installment_amount': 46500000, 'channel_id': 1000501, 'monthly_installment': 7750000, 'tenure': 6, 'total_amount': 46500000}, 'name': 'Airpay CC Installment [label_bank_ocbc #6x]', 'option_info': '1000501-19005017'}, {'disabled_reason': None, 'data': {'bank_name': 'OCBC', 'down_payment': 0, 'name': '12x # 0%', 'interest_rate': 0, 'option_id': None, 'bank_id': 3430, 'installment_amount': 46500000, 'channel_id': 1000501, 'monthly_installment': 3875000, 'tenure': 12, 'total_amount': 46500000}, 'name': 'Airpay CC Installment [label_bank_ocbc #12x]', 'option_info': '1000501-19005018'}], 'bank_id': 3430, 'bank_logo': 'https://mall.shopee.sg/static/images/bank_logo/ic_bank_ocbc.png'}], 'channel_name': 'label_cc_installment', 'is_cc': True, 'plans': None, 'channel_ic': 'ic_paymentoption_ccinstallment'}], 'view_count': 9765, 'voucher_info': None, 'current_promotion_has_reserve_stock': False, 'liked_count': 491, 'show_official_shop_label': False, 'price_min_before_discount': 54900000, 'show_discount': 15, 'preview_info': None, 'flag': 524290, 'exclusive_price_info': None, 'current_promotion_reserved_stock': 0, 'wholesale_tier_list': [], 'group_buy_info': None, 'shopee_verified': False, 'item_has_post': False, 'hidden_price_display': None, 'transparent_background_image': '68ce24874257ec3c593d0d118e9cf785', 'welcome_package_info': None, 'discount_stock': 8, 'coin_info': {'spend_cash_unit': 1000, 'coin_earn_items': []}, 'is_adult': False, 'currency': 'SGD', 'raw_discount': 15, 'is_preferred_plus_seller': False, 'is_category_failed': False, 'price_min': 46500000, 'can_use_bundle_deal': False, 'cb_option': 0, 'brand': '', 'stock': 8, 'status': 1, 'bundle_deal_id': 0, 'is_group_buy_item': None, 'description': "Brand New Set\r\n\r\nGalaxy Tab S6 Lite is your super portable note-taking, go-getting companion. It comes with a large 10.4 inch display on a slim and light build, One UI 2 on Android, and S Pen in-box and ready to go. Whether you're drawing, learning or gaming, this is the tablet made to be in the moment.\r\n\r\nGalaxy Tab S6 Lite is slim and lightweight thanks to its seamless, metal unibody. It slips easily into a small tote for true portability and minimalist style. \r\n\r\nKeeping up with lectures is a breeze with S Pen. When taking notes, you can jot first and change colors later. Quickly sort through memos when you save with searchable tags. Even write directly onto PDFs to cut the study clutter. When it's finally crunch time, you'll be organised and ready.\r\n\r\nS Pen is a bundle of writing instruments in one. Its natural grip, low latency and impressive pressure sensitivity will make it your go-to for everything from drawing to editing documents. And don't worry about misplacing the S Pen, thanks to the tablet's magnetic holder.\r\n\r\nDisplay : 10.4 inches\r\nExternal Memory Support Slot : Yes , MicroSD (Up to 1TB)\r\n64GB ROM + 4GB RAM\r\n8MP Rear Camera\r\n5MP Selfie Camera\r\n7040 mAh Big battery\r\n\r\nExport set with local seller warranty", 'flash_sale': None, 'models': [{'itemid': 2590867516, 'status': 1, 'current_promotion_reserved_stock': 0, 'name': 'Pink', 'promotionid': 58388, 'price': 46500000, 'price_stocks': [{'model_id': 5839808211, 'stockout_time': 1613452764, 'region': 'SG', 'rebate': 2000000, 'price': 46500000, 'promotion_type': 1, 'allocated_stock': 0, 'shop_id': 165420215, 'end_time': 1613663940, 'stock_breakdown_by_location': [], 'item_id': 2590867516, 'promotion_id': 58388, 'purchase_limit': 1, 'start_time': 1613452860, 'stock': 0}, {'model_id': 5839808211, 'stockout_time': 1612672967, 'region': 'SG', 'rebate': None, 'price': 54900000, 'promotion_type': 0, 'allocated_stock': None, 'shop_id': 165420215, 'end_time': None, 'stock_breakdown_by_location': [], 'item_id': 2590867516, 'promotion_id': 0, 'purchase_limit': None, 'start_time': None, 'stock': 0}], 'current_promotion_has_reserve_stock': False, 'currency': 'SGD', 'normal_stock': 0, 'extinfo': {'seller_promotion_limit': 1, 'has_shopee_promo': True, 'group_buy_info': None, 'holiday_mode_old_stock': None, 'tier_index': [0], 'seller_promotion_refresh_time': 1613663940}, 'price_before_discount': 54900000, 'modelid': 5839808211, 'sold': 12, 'stock': 0}, {'itemid': 2590867516, 'status': 1, 'current_promotion_reserved_stock': 0, 'name': 'Blue', 'promotionid': 58388, 'price': 46500000, 'price_stocks': [{'model_id': 51655477750, 'stockout_time': 1613452764, 'region': 'SG', 'rebate': 2000000, 'price': 46500000, 'promotion_type': 1, 'allocated_stock': 0, 'shop_id': 165420215, 'end_time': 1613663940, 'stock_breakdown_by_location': [], 'item_id': 2590867516, 'promotion_id': 58388, 'purchase_limit': 1, 'start_time': 1613452860, 'stock': 0}, {'model_id': 51655477750, 'stockout_time': 1612146775, 'region': 'SG', 'rebate': None, 'price': 54900000, 'promotion_type': 0, 'allocated_stock': None, 'shop_id': 165420215, 'end_time': None, 'stock_breakdown_by_location': [], 'item_id': 2590867516, 'promotion_id': 0, 'purchase_limit': None, 'start_time': None, 'stock': 0}], 'current_promotion_has_reserve_stock': False, 'currency': 'SGD', 'normal_stock': 0, 'extinfo': {'seller_promotion_limit': 1, 'has_shopee_promo': True, 'group_buy_info': None, 'holiday_mode_old_stock': None, 'tier_index': [2], 'seller_promotion_refresh_time': 1613663940}, 'price_before_discount': 54900000, 'modelid': 51655477750, 'sold': 65, 'stock': 0}, {'itemid': 2590867516, 'status': 1, 'current_promotion_reserved_stock': 0, 'name': 'Gray', 'promotionid': 58388, 'price': 46500000, 'price_stocks': [{'model_id': 70652051151, 'stockout_time': 1613452764, 'region': 'SG', 'rebate': 2000000, 'price': 46500000, 'promotion_type': 1, 'allocated_stock': 0, 'shop_id': 165420215, 'end_time': 1613663940, 'stock_breakdown_by_location': [], 'item_id': 2590867516, 'promotion_id': 58388, 'purchase_limit': 1, 'start_time': 1613452860, 'stock': 0}, {'model_id': 70652051151, 'stockout_time': 0, 'region': 'SG', 'rebate': None, 'price': 54900000, 'promotion_type': 0, 'allocated_stock': None, 'shop_id': 165420215, 'end_time': None, 'stock_breakdown_by_location': [], 'item_id': 2590867516, 'promotion_id': 0, 'purchase_limit': None, 'start_time': None, 'stock': 8}], 'current_promotion_has_reserve_stock': False, 'currency': 'SGD', 'normal_stock': 8, 'extinfo': {'seller_promotion_limit': 1, 'has_shopee_promo': True, 'group_buy_info': None, 'holiday_mode_old_stock': None, 'tier_index': [1], 'seller_promotion_refresh_time': 1613663940}, 'price_before_discount': 54900000, 'modelid': 70652051151, 'sold': 109, 'stock': 8}], 'has_low_fulfillment_rate': False, 'price': 46500000, 'shop_location': None, 'tier_variations': [{'images': ['dd6712ad6486c287be4f4c4ae82d5bb4', '228c0a8b72a457c99e420f980fbe6647', '028138dce1f06a573864ed58033267aa'], 'properties': [], 'type': 0, 'name': 'Colour', 'options': ['Pink', 'Gray', 'Blue']}], 'makeups': None, 'welcome_package_type': 0, 'show_official_shop_label_in_normal_position': None, 'item_type': 0}, 'version': '84fbe13733fdcb30d4c53c991d682692', 'data': None, 'error_msg': None, 'error': None}
You are iterating over dictionary item. Your iteration is making a dictionary get call on every element of item, that's is where the error is coming.
To get what you want, you don't have to iterate:
site_json['item'].get('price_max_before_discount')
The problem here is that at some point you are trying to access the value "price_max_before_discount" from a string, not a dictionary that includes that key. Thus, this error accurs AttributeError: 'str' object has no attribute 'get'.
This happens because you are iterating through the "item" dictionary. In each iteration you get a key. For example you get "itemid" (the key, not the value) and you try to get "price_max_before_discount" from it. But it's just a string!
The solution:
site_json['item']['price_max_before_discount']
Here you are getting the "item" json and from there getting the value of "price_max_before_discount"
I was trying to read the 30 first comments from a json format with this code is what wrote:
list_of_comments=list()
while (j<30):
list_of_comments.append((talkbacks["data"]["list"][j]["content"],talkbacks["data"]["list"][j]
["positive"],talkbacks["data"]["list"][j]["negative"]))
when i run this code it gives me the "list indices must be integers or slices, not str" error. I cant see what im missing here, probably something with the dict/list locations. please save me
this is my json:
{'result': 'success', 'data': {'list': [{'id': 45969880, 'fatherId': 0, 'writer': 'מגלה שקרנים ', 'content': 'חחחחחחח עוד100שמנ חחחחחחחחחחחחחחחח תפי על אבא שלכם', 'createDate': '23:20 23.07.20', 'c1': '2020-07-23 23:20:09', 'positive': 0, 'negative': 0, 'children': []}, {'id': 45965215, 'fatherId': 0, 'writer': 'וואלה', 'content': 'מה שלא יכחד לעולם זה "המומחים המזהירים"', 'createDate': '15:24 23.07.20', 'c1': '2020-07-23 15:24:37', 'positive': 0, 'negative': 0, 'children': []}, {'id': 45965179, 'fatherId': 0, 'writer': 'נו', 'content': 'אולי הדובים הלבנים יעלמו אבל מה שלא יכחד לעולם אלה הפילים הלבנים של ממשלות ישראל.', 'createDate': '15:20 23.07.20', 'c1': '2020-07-23 15:20:57', 'positive': 1, 'negative': 0, 'children': []}, {'id': 45958898, 'fatherId': 0, 'writer': '.', 'content': 'אל תאמינו למומחים כי הם לא מומחים\n\n\n\n\n\n\n\n\nחרטא\n\n\n', 'createDate': '06:28 23.07.20', 'c1': '2020-07-23 06:28:43', 'positive': 0, 'negative': 0, 'children': []}, {'id': 45958450, 'fatherId': 0, 'writer': 'בני האדם', 'content': 'העיקר שהחיה שהכי מסוכנת בעולם לא תיכחד', 'createDate': '03:08 23.07.20', 'c1': '2020-07-23 03:08:20', 'positive': 1, 'negative': 0, 'children': []}, {'id': 45958360, 'fatherId': 0, 'writer': 'דובי', 'content': 'המומחים ייכחדו הרבה לפנינו...אז שלא "ידאגו" לנו !', 'createDate': '02:13 23.07.20', 'c1': '2020-07-23 02:13:54', 'positive': 2, 'negative': 0, 'children': []}, {'id': 45958315, 'fatherId': 0, 'writer': 'ש', 'content': 'נקווה שהאדם ייכחד קצת קודם', 'createDate': '01:59 23.07.20', 'c1': '2020-07-23 01:59:30', 'positive': 0, 'negative': 0, 'children': []}, {'id': 45958030, 'fatherId': 0, 'writer': ' רפואה משלימה', 'content': 'אביגדור ליברמן: אז עם מי יקים גנץ קואליציה ?', 'createDate': '00:45 23.07.20', 'c1': '2020-07-23 00:45:15', 'positive': 1, 'negative': 0, 'children': []}, {'id': 45958012, 'fatherId': 0, 'writer': 'אל דאגה', 'content': 'עד אז החוקרים ייכחדו לפניהם', 'createDate': '00:40 23.07.20', 'c1': '2020-07-23 00:40:34', 'positive': 2, 'negative': 0, 'children': []}, {'id': 45957755, 'fatherId': 0, 'writer': 'רוני', 'content': 'דוקטור תציל אותי אני מאוהב תתעוררוחחחחח', 'createDate': '23:59 22.07.20', 'c1': '2020-07-22 23:59:39', 'positive': 0, 'negative': 0, 'children': []}, {'id': 45957754, 'fatherId': 0, 'writer': 'טלי', 'content': 'לא נורא יש לנו את שמחה גואטה מקסימום נישלח אותה לאנטראטיקה תעשה תצוגות אופנה לדאבות זן חדש במקום דובי קוטב דאבות', 'createDate': '23:59 22.07.20', 'c1': '2020-07-22 23:59:39', 'positive': 2, 'negative': 0, 'children': []}, {'id': 45957607, 'fatherId': 0, 'writer': 'תבדקו או תנחשו', 'content': 'לא הבנתי את מי המזהירים המומחים הללו?\nאותי? אותך?\nמליוני זנים, כם דל בני אדם, נכחדו בעולם הזה ואחרים צצו. מה יש להזהיר פה ואת מי?', 'createDate': '23:38 22.07.20', 'c1': '2020-07-22 23:38:47', 'positive': 1, 'negative': 1, 'children': []}, {'id': 45957194, 'fatherId': 0, 'writer': 'גוגו', 'content': 'מתי יכחדו מרוקאים. "ביביסטים".?', 'createDate': '22:57 22.07.20', 'c1': '2020-07-22 22:57:56', 'positive': 3, 'negative': 4, 'children': [{'id': 45957295, 'fatherId': 45957194, 'writer': 'מיקי', 'content': 'לא יקרה, אותנו אי אפשר להעמיס לקרונות רכבת...אתם רגילים ללכת כצאן לטבח אנחנו פחות בנויים לזה.ההימור שלי אתה תכחד מהר יותר.', 'createDate': '23:06 22.07.20', 'c1': '2020-07-22 23:06:21', 'positive': 0, 'negative': 0, 'children': []}, {'id': 45957439, 'fatherId': 45957194, 'writer': 'אמר', 'content': 'הלוואי במהרה בימינו ', 'createDate': '23:18 22.07.20', 'c1': '2020-07-22 23:18:44', 'positive': 0, 'negative': 0, 'children': []}]}, {'id': 45957163, 'fatherId': 0, 'writer': 'לשפוט ועוד לשפוט', 'content': 'במקום לדבר שטויות כאן אולי תנסו להמציא דרך להפחית את פחיטת גזי החממה כי זה אניתי גם כן בדיוק כמו הקורונה . אל תזלזלו תנסו לחשוב על איך להציל אותם ואותנו בעתיד הקרוב', 'createDate': '22:55 22.07.20', 'c1': '2020-07-22 22:55:08', 'positive': 0, 'negative': 0, 'children': [{'id': 45965186, 'fatherId': 45957163, 'writer': 'נו', 'content': 'הפסקתי לאכול חומוס.', 'createDate': '15:21 23.07.20', 'c1': '2020-07-23 15:21:32', 'positive': 0, 'negative': 0, 'children': []}]}, {'id': 45957128, 'fatherId': 0, 'writer': 'רון', 'content': 'מעניין את הביצה השמאלית \nאפשר לחשוב שכל יום אני רואה דוב קוטב , \nיותר חרבנה שהממשלה רוכשת ב100 מיליון שקל רכבים חדשים לצי הממשלתי .', 'createDate': '22:52 22.07.20', 'c1': '2020-07-22 22:52:49', 'positive': 1, 'negative': 3, 'children': [{'id': 45957187, 'fatherId': 45957128, 'writer': 'לשפוט ועוד לשפוט', 'content': 'אז תחשוב פעמיים לפני כי הביצה הימנית שלך אולי כן יחשוב על איך לשרוד, כי כסף ורכבים ממשלתיים הם ממש לא קשורים להצלת העולם ', 'createDate': '22:57 22.07.20', 'c1': '2020-07-22 22:57:28', 'positive': 0, 'negative': 0, 'children': []}]}, {'id': 45956967, 'fatherId': 0, 'writer': 'יואב', 'content': 'העולם יכחד לפני', 'createDate': '22:36 22.07.20', 'c1': '2020-07-22 22:36:11', 'positive': 0, 'negative': 1, 'children': []}, {'id': 45956939, 'fatherId': 0, 'writer': 'God', 'content': 'iT’s OK, U Ain’T GoNna maKe iT ThaT FaR AnYWaY... HaVe FuN... iT Won’T TakE LonG.', 'createDate': '22:33 22.07.20', 'c1': '2020-07-22 22:33:42', 'positive': 0, 'negative': 2, 'children': []}, {'id': 45956698, 'fatherId': 0, 'writer': 'המשקיף', 'content': 'בקצב כזה, ספק רב אם בני האדם ישרדו עד 2100. ודובי הקוטב - סיכוי טוב שישארו הרבה אחרינו.', 'createDate': '22:11 22.07.20', 'c1': '2020-07-22 22:11:26', 'positive': 4, 'negative': 1, 'children': [{'id': 45957092, 'fatherId': 45956698, 'writer': 'אבנר', 'content': 'מצויין. להם מגיע!', 'createDate': '22:49 22.07.20', 'c1': '2020-07-22 22:49:50', 'positive': 0, 'negative': 0, 'children': []}]}, {'id': 45955752, 'fatherId': 0, 'writer': 'א', 'content': 'לא צריך לעשות הרבה. פשוט להעביר אוכלוסיות של דובי קוטב לקוטב הדרומי. ', 'createDate': '20:37 22.07.20', 'c1': '2020-07-22 20:37:41', 'positive': 3, 'negative': 2, 'children': [{'id': 45956703, 'fatherId': 45955752, 'writer': 'ב', 'content': 'גם שם הקרחונים נמסים אם אתה לא מעודכן', 'createDate': '22:11 22.07.20', 'c1': '2020-07-22 22:11:50', 'positive': 0, 'negative': 0, 'children': []}, {'id': 46011605, 'fatherId': 45955752, 'writer': 'מיכאל', 'content': 'גם חשבתי על זה, והט*פש שכתב שגם שם הקרחונים נמסים, לא מבין שהקוטב הדרומי יושב על יבשת (אנטרטיקה) ולא על ים כמו הקוטב הצפוני, חוץ מזה שהוא קר ב 20 מעלות בממוצע מהצפוני.', 'createDate': '00:12 27.07.20', 'c1': '2020-07-27 00:12:08', 'positive': 0, 'negative': 0, 'children': []}]}, {'id': 45951584, 'fatherId': 0, 'writer': 'רון', 'content': 'חבל על הדובים, הכל בגלל ביבי', 'createDate': '14:15 22.07.20', 'c1': '2020-07-22 14:15:58', 'positive': 2, 'negative': 0, 'children': []}, {'id': 45951006, 'fatherId': 0, 'writer': 'נו', 'content': 'איזה קישקוש מטופש.', 'createDate': '13:31 22.07.20', 'c1': '2020-07-22 13:31:22', 'positive': 3, 'negative': 1, 'children': []}, {'id': 45948558, 'fatherId': 0, 'writer': 'תרגיעו', 'content': 'נמאס כבר מדובי הקוטב האכזריים שכל שנה רוצחים אלפי כלבי ים תמימים וחמודים שלא עשו להם שום דבר רע, כולל גורים חסרי ישע! לדובי הקוטב אין אויבים טבעיים (האויבים נכחדו מזמן) והם מתרבים בלי סוף. אם יפחת מספרם אז כלבי הים החמודים יוכלו סוף סוף לנשום לרווחה', 'createDate': '09:45 22.07.20', 'c1': '2020-07-22 09:45:44', 'positive': 5, 'negative': 9, 'children': [{'id': 45949265, 'fatherId': 45948558, 'writer': 'אחד', 'content': 'תגובה מטומטמת של אדם מטומטם..ממי שכן נמאס זה מאנושות שמכחידה את בעלי החיים..ואם יפחת מיספרם סוף סוף בעליי החיים יינשמו לרווחה', 'createDate': '10:50 22.07.20', 'c1': '2020-07-22 10:50:43', 'positive': 0, 'negative': 0, 'children': []}, {'id': 45957042, 'fatherId': 45948558, 'writer': 'tt', 'content': 'תגובה דבילית וגם מי שהגיב לך אידיוט.', 'createDate': '22:44 22.07.20', 'c1': '2020-07-22 22:44:56', 'positive': 0, 'negative': 0, 'children': []}]}, {'id': 45947887, 'fatherId': 0, 'writer': 'הבלופר מבלפור', 'content': 'מתי כבר נקבל כתבה על המוסלמים שהם בסכנת הכחדה...', 'createDate': '08:47 22.07.20', 'c1': '2020-07-22 08:47:37', 'positive': 8, 'negative': 0, 'children': [{'id': 45956953, 'fatherId': 45947887, 'writer': 'J', 'content': 'עם כל העצב שטמון בתגובה שלך, היא אחת המצחיקות שקראתי מאז פרוץ המגיפה...', 'createDate': '22:35 22.07.20', 'c1': '2020-07-22 22:35:11', 'positive': 0, 'negative': 0, 'children': []}, {'id': 46011614, 'fatherId': 45947887, 'writer': 'מיכאל', 'content': 'בסין מצאו שיטה', 'createDate': '00:12 27.07.20', 'c1': '2020-07-27 00:12:58', 'positive': 0, 'negative': 0, 'children': []}]}, {'id': 45947590, 'fatherId': 0, 'writer': 'דובי', 'content': 'מי שלא מסתגל נכחד. קוראים לזה אבולוציה. זה לא רעיון חדש... החוקרים לא שמעו על אבולוציה?', 'createDate': '08:20 22.07.20', 'c1': '2020-07-22 08:20:28', 'positive': 3, 'negative': 6, 'children': [{'id': 45947883, 'fatherId': 45947590, 'writer': 'הבלופר מבלפור', 'content': 'אתה חכם. איזה עומק מסתתר בתגובתך. שאפו.', 'createDate': '08:47 22.07.20', 'c1': '2020-07-22 08:47:11', 'positive': 0, 'negative': 0, 'children': []}, {'id': 45948695, 'fatherId': 45947590, 'writer': 'חי בר', 'content': 'דובי צודק! הגיע זמן שהאדם יפסיק להתערב בטבע כאילו הוא אלוהים שקובע איזה מין יחיה ואיזה לא. החוקרים רק רוצים עוד ועוד כסף', 'createDate': '09:58 22.07.20', 'c1': '2020-07-22 09:58:54', 'positive': 0, 'negative': 0, 'children': []}, {'id': 45957054, 'fatherId': 45947590, 'writer': 'tt', 'content': 'הסתגלות לוקחת מאות ואלפי שנים, אנחנו עושים נזק מהר מהר ', 'createDate': '22:45 22.07.20', 'c1': '2020-07-22 22:45:48', 'positive': 0, 'negative': 0, 'children': []}, {'id': 45957462, 'fatherId': 45947590, 'writer': 'האמת', 'content': 'tt - המטאור שפגע בחצי האי יוקטן עשה נזק מירבי ברגע אחד... זה מה יש, בני אדם הם חלק מהטבע והנזק שאנחנו עושים לא שונה מהנזק ששימפנזים עושים עם מקל כשהם אוכלים נמלים.... חוץ מהסקלה כמובן...', 'createDate': '23:22 22.07.20', 'c1': '2020-07-22 23:22:18', 'positive': 0, 'negative': 0, 'children': []}]}], 'total': 39, 'discussions': 24}}
do it the "python way" :-) (it's called list comprehensions)
list_of_comments = [(comment['content'],comment['positive'],comment['negative']) for comment in talkbacks['data']['list'][:30]]
good luck
Python Newbie here. I am using http://myjson.com/api to host a json file store and am having trouble using Python to PUT using their API.
I have a dict called budget that I would like to PUT to a specific API endpoint. It says to "Send updated JSON as String".
This the response when I type budget which I believe is a dict?:
{'spend': [{'isTransfer': False, 'catTypeFilter': 'Personal', 'rbal': 0.0, 'st'
1, 'isIncome': False, 'ex': False, 'isExpense': True, 'cat': 'Auto Insurance',
'amt': 150.0, 'date': '02/01/2016', 'aamt': 0.0, 'bgt': 150.0, 'type': 1, 'tbgt
: 1800.0, 'islast': False, 'id': 65369859, 'ramt': 0, 'period': 12, 'pid': 14},
{'isTransfer': False, 'rbal': -929.44, 'st': 3, 'ex': False, 'isExpense': True,
'cat': 'Auto Payment', 'amt': 1816.44, 'bgt': 887.0, 'type': 0, 'isIncome': Fal
e, 'catTypeFilter': 'Personal', 'id': 65369856, 'ramt': 0, 'pid': 14}, {'isTran
fer': False, 'rbal': 183.31, 'st': 1, 'ex': False, 'isExpense': True, 'cat': 'G
s & Fuel', 'amt': 266.69, 'bgt': 450.0, 'type': 0, 'isIncome': False, 'catTypeF
lter': 'Personal', 'id': 65369851, 'ramt': 0, 'pid': 14}, {'roll': True, 'isTra
sfer': False, 'rbal': -188.32, 'st': 3, 'isIncome': False, 'ex': False, 'isExpe
se': True, 'cat': 'Service & Parts', 'amt': 238.32, 'bgt': 50.0, 'type': 0, 'ca
TypeFilter': 'Personal', 'id': 65369855, 'ramt': 238.32, 'pid': 14}, {'isTransf
r': False, 'rbal': -14.99, 'st': 3, 'ex': False, 'isExpense': True, 'cat': 'Int
rnet', 'amt': 49.99, 'bgt': 35.0, 'type': 0, 'isIncome': False, 'catTypeFilter'
'Personal', 'id': 65369845, 'ramt': 0, 'pid': 13}, {'isTransfer': False, 'rbal
: -88.04, 'st': 3, 'ex': False, 'isExpense': True, 'cat': 'Mobile Phone', 'amt'
245.04, 'bgt': 157.0, 'type': 0, 'isIncome': False, 'catTypeFilter': 'Personal
, 'id': 65369858, 'ramt': 0, 'pid': 13}, {'isTransfer': False, 'rbal': 80.63, '
t': 1, 'ex': False, 'isExpense': True, 'cat': 'Utilities', 'amt': 74.37, 'bgt':
155.0, 'type': 0, 'isIncome': False, 'catTypeFilter': 'Personal', 'id': 6536985
, 'ramt': 0, 'pid': 13}, {'isTransfer': False, 'rbal': 74.0, 'st': 1, 'ex': Fal
e, 'isExpense': True, 'cat': 'Life Insurance', 'amt': 0, 'bgt': 74.0, 'type': 0
'isIncome': False, 'catTypeFilter': 'Personal', 'id': 65369843, 'ramt': 0, 'pi
': 11}, {'isTransfer': False, 'rbal': -31.55, 'st': 3, 'ex': False, 'isExpense'
True, 'cat': 'Groceries', 'amt': 831.55, 'bgt': 800.0, 'type': 0, 'isIncome':
alse, 'catTypeFilter': 'Personal', 'id': 65369842, 'ramt': 0, 'pid': 7}, {'isTr
nsfer': False, 'rbal': 6.73, 'st': 2, 'ex': False, 'isExpense': True, 'cat': 'R
staurants', 'amt': 93.27, 'bgt': 100.0, 'type': 0, 'isIncome': False, 'catTypeF
lter': 'Personal', 'id': 65369840, 'ramt': 0, 'pid': 7}, {'isTransfer': False,
rbal': 38.0, 'st': 1, 'ex': False, 'isExpense': True, 'cat': 'Charity', 'amt':
, 'bgt': 38.0, 'type': 0, 'isIncome': False, 'catTypeFilter': 'Personal', 'id':
65369860, 'ramt': 0, 'pid': 8}, {'isTransfer': False, 'rbal': 60.0, 'st': 1, 'e
': False, 'isExpense': True, 'cat': 'Gift', 'amt': 0, 'bgt': 60.0, 'type': 0, '
sIncome': False, 'catTypeFilter': 'Personal', 'id': 65369857, 'ramt': 0, 'pid':
8}, {'isTransfer': False, 'rbal': 560.0, 'st': 1, 'ex': False, 'isExpense': Tru
, 'cat': 'Tithes and Offerings', 'amt': 0, 'bgt': 560.0, 'type': 0, 'isIncome':
False, 'catTypeFilter': 'Personal', 'id': 65369846, 'ramt': 0, 'pid': 8}, {'isT
ansfer': False, 'rbal': -12.0, 'st': 3, 'ex': False, 'isExpense': True, 'cat':
Unknown', 'amt': 112, 'bgt': 100.0, 'type': 0, 'isIncome': False, 'catTypeFilte
': 'Personal', 'id': 65369853, 'ramt': 0, 'pid': None}, {'roll': True, 'isTrans
er': False, 'rbal': 1150.0, 'st': 1, 'isIncome': False, 'ex': False, 'isExpense
: True, 'cat': 'Home Insurance', 'amt': -1100.0, 'bgt': 50.0, 'type': 0, 'catTy
eFilter': 'Personal', 'id': 65369848, 'ramt': -1100.0, 'pid': 12}, {'isTransfer
: False, 'rbal': 12.0, 'st': 1, 'ex': False, 'isExpense': True, 'cat': 'Home Se
vices', 'amt': 0, 'bgt': 12.0, 'type': 0, 'isIncome': False, 'catTypeFilter': '
ersonal', 'id': 65369849, 'ramt': 0, 'pid': 12}, {'isTransfer': False, 'rbal':
.09, 'st': 2, 'ex': False, 'isExpense': True, 'cat': 'Mortgage & Rent', 'amt':
395.91, 'bgt': 2400.0, 'type': 0, 'isIncome': False, 'catTypeFilter': 'Personal
, 'id': 65369854, 'ramt': 0, 'pid': 12}, {'isTransfer': False, 'rbal': -35.97,
st': 3, 'ex': False, 'isExpense': True, 'cat': 'Unknown', 'amt': 185.97, 'bgt':
150.0, 'type': 0, 'isIncome': False, 'catTypeFilter': 'Personal', 'id': 6536984
, 'ramt': 0, 'pid': None}, {'isTransfer': False, 'rbal': 75.0, 'st': 1, 'ex': F
lse, 'isExpense': True, 'cat': 'Hair', 'amt': 0, 'bgt': 75.0, 'type': 0, 'isInc
me': False, 'catTypeFilter': 'Personal', 'id': 65369861, 'ramt': 0, 'pid': 4},
'isTransfer': False, 'rbal': -15.57, 'st': 3, 'ex': False, 'isExpense': True, '
at': 'Unknown', 'amt': 165.57, 'bgt': 150.0, 'type': 0, 'isIncome': False, 'cat
ypeFilter': 'Personal', 'id': 65369844, 'ramt': 0, 'pid': None}, {'roll': True,
'isTransfer': False, 'rbal': 14122.0, 'st': 1, 'isIncome': False, 'ex': False,
isExpense': True, 'cat': 'Property Tax', 'amt': -13508.0, 'bgt': 614.0, 'type':
0, 'catTypeFilter': 'Personal', 'id': 65369841, 'ramt': -13508.0, 'pid': 19}],
income': [{'isTransfer': False, 'rbal': 1319.87, 'st': 1, 'ex': False, 'isExpen
e': False, 'cat': 'Unknown', 'amt': 6680.13, 'bgt': 8000.0, 'type': 0, 'isIncom
': True, 'catTypeFilter': 'Personal', 'id': 65369852, 'ramt': 0, 'pid': None}]}
This is my script:
requests.put('https://api.myjson.com/bins/1quvq', data=str(budget))
But I keep getting a 500 Error:
b'{"status":500,"message":"Internal Server Error","more_info":"undefined method`string\' for #\\u003cPhusionPassenger::Utils::TeeInput:0x007f83edc7eac0\\u003e"}'
What am I doing wrong?
Ok this works for me: -
import requests
budget = {'s': 'd'}
r = requests.put('https://api.myjson.com/bins/1quvq', json=budget)
print r.content
If you are still having a problem with your data you need to include your full data in the question. Your dict seems to have been truncated at the edges.