Reputation: 383
I have a JSON output im getting from an API and im trying to extract the nested values from 'rows' and to access 'cells' key within rows.
Here is the JSON output
"rows": [
{
"id": 6770063759566724,
"rowNumber": 1,
"expanded": true,
"createdAt": "2022-01-27T17:04:11Z",
"modifiedAt": "2022-01-27T17:04:11Z",
"cells": [
{
"columnId": 2775064444725124,
"value": "Smith",
"displayValue": "Smith"
},
{
"columnId": 7278664072095620,
"value": "John",
"displayValue": "John"
},
{
"columnId": 1649164537882500,
"value": 12.0,
"displayValue": "12"
},
{
"columnId": 6152764165252996,
"value": "Gilbert",
"displayValue": "Gilbert"
},
{
"columnId": 3900964351567748,
"value": "Webhook Test",
"displayValue": "Webhook Test"
}
]
},
Here is my code
I need each columnID within cells and the value within cells. These values will then be recorded into my Django project. Appreciate the help.
This is the output of of print(cells)
{6770063759566724: [{'columnId': 2775064444725124, 'value': 'Smith', 'displayValue': 'Smith'}, {'columnId': 7278664072095620, 'value': 'John', 'displayValue': 'John'}, {'columnId': 1649164537882500, 'value': 12.0, 'displayValue': '12'}, {'columnId': 6152764165252996, 'value': 'Gilbert', 'displayValue': 'Gilbert'}, {'columnId': 3900964351567748, 'value': 'Webhook Test', 'displayValue': 'Webhook Test'}]}
for r in response_info ['rows']:
try:
row_id = r['id']
rowNumber = r['rowNumber']
if SmartSheetData.objects.filter(sheet_id = sheet, row_id = row_id):
print("Updating Sheet rows")
print('<--Row ID-->%s' %row_id)
print('<--Row Number-->%s' %rowNumber)
SmartSheetData.objects.filter(sheet_id = sheet, row_id = row_id).update(row_number = rowNumber)
# GETS CELL VALUES
print('Getting Cell Values')
cells = {}
cells[r['id']] = r['cells']
print(cells)
columnId = cells.get('columnId')
value = cells.get('value')
print('<--Column ID-->%s' %column_id)
print('<--Value-->%s' %value)
if SmartSheetData.objects.filter(sheet_id = sheet, row_id = row_id):
print("Updating row cell values")
print('<--Row ID-->%s' %row_id)
print('<--Row Number-->%s' %rowNumber)
print('<--Column ID-->%s' %column_id)
print('<--Cell Value-->%s' %value)
SmartSheetData.objects.filter(sheet_id = sheet, row_id = row_id).update(row_cell = value)
except Exception as err5:
print ("Missing row values, skipping", str(err5))
Upvotes: 0
Views: 67
Reputation: 8192
Hopefully this is correct and you'll be able to take it from here
for nrow, row in enumerate( response_info ['rows']) :
# use dict.get method to supply a default for missing keys instead of crashing.
# Here, an empty list can be iterated over (zero times) in the inner loop.
cells = row.get('cells', [])
for ncol, cell in enumerate( cells):
col_id = cell.get( "columnId", None)
value = cell.get( "value", None)
# what you do with these things is up to you
print( f"Row {nrow} cell {ncol} id : value = {col_id} : {value}")
Upvotes: 1