1

Context: Using Visual Studio Code, trying to convert my JSON response into a Python list, so I can add it to a Google Sheet.

I'd like to convert my response into a List of JSON Lists (like the "working example" below)

Working Example

RandomJson = [
    ['hello',2],
    ["hi",3]
]

bla = sheet.values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID, range='sheet1!A1', valueInputOption="USER_ENTERED", body={"values":RandomJson}).execute()

I've tried a number of ways, but I cannot get "My Data Set" into the "Desired Format"

Can anybody help please?

My Data Set

{
  "data": {
    "tokens": [
      {
        "name": "FMX Token",
        "symbol": "FMXT"
      },
      {
        "name": "HeavensGate",
        "symbol": "HATE"
      },
      {
        "name": "Shrimp Swap",
        "symbol": "Shrimp"
      }
    ]
  }
}

Desired Format

RandomJson = [
    ["FMX Token","FMXT"],
    ["HeavensGate","HATE"],
    ["Shrimp Swap","Shrimp"]
]

Edit - Full Code

I have made a change suggested in the comments, and also added "j = json.loads(JsonData)"

I'm now getting an error:

"googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets//values/sheet1%21A1?valueInputOption=USER_ENTERED&alt=json returned "Invalid JSON payload received. Unknown name "FMX Token" at 'data.values': Cannot find field."

import requests
import gspread
import json
import os.path
import pprint
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2 import service_account

SERVICE_ACCOUNT_FILE = 'CredEDs.json'
SCOPES = ["https://spreadsheets.google.com/feeds","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]

creds = None
creds = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

SAMPLE_SPREADSHEET_ID = ''

service = build('sheets','v4',credentials=creds)

sheet = service.spreadsheets()

headers = {
    'authority': 'api.thegraph.com',
    'accept': '*/*',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
    'content-type': 'application/json',
    'origin': 'https://info.uniswap.org',
    'sec-fetch-site': 'cross-site',
    'sec-fetch-mode': 'cors',
    'sec-fetch-dest': 'empty',
    'referer': 'https://info.uniswap.org',
    'accept-language': 'en-GB,en;q=0.9,es-419;q=0.8,es;q=0.7,en-US;q=0.6',
}

data = rb'{"operationName":"tokens","variables":{"skip":500},"query":"query tokens($skip: Int\u0021) {\n tokens(first: 500, skip: $skip) {\n name\n symbol\n}\n}\n"}'
response = requests.post('https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2', headers=headers, data=data)

JsonData = response.text

j = json.loads(JsonData)

result = {token['name']: token['symbol'] for token in j['data']['tokens']}

bla = sheet.values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID, range='sheet1!A1', valueInputOption="USER_ENTERED", body={"values":result}).execute()

1 Answer 1

9

It's as simple as:

result = [[token['name'], token['symbol']] for token in data['data']['tokens']]
Sign up to request clarification or add additional context in comments.

14 Comments

Thanks for the response! Unfortunately I got: "TypeError: byte indices must be integers or slices, not str" Here is a larger sample of the code just for context ``` data = rb'{"operationName":"tokens","variables":{"skip":500},"query":"query tokens($skip: Int\u0021) {\n tokens(first: 500, skip: $skip) {\n name\n symbol\n}\n}\n"}' response = requests.post('api.thegraph.com/subgraphs/name/uniswap/uniswap-v2', headers=headers, data=data) JsonData = response.text result = {token['name']: token['symbol'] for token in data['data']['tokens']} print (result) ```
Unfortunately, your example probably not exactly as you described... please include some more code, and question? Is the example you provided is a string or converted via json module?
Firstly then, if it is another issue, thanks @go2nivana for helping out. adirabargil I've added more code and another error into the "Edit" section
It looks like the response is in String format, so you need to convert the string to JSON. import json JSONTypeData = json.loads(JsonData)
Hi @AnkitSahay, thanks for the suggestion, I added that (see Edited section in the original post) and I'm getting a strange error, but I think it is a step closer to victory!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.