JSON到Python列表

上下文:使用 Visual Studio Code,尝试将我的 JSON 响应转换为 Python 列表,以便我可以将其添加到 Google Sheet。

我想将我的响应转换为 JSON 列表列表(如下面的“工作示例”)

工作示例

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

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

我尝试了多种方法,但无法将“我的数据集”转换为“所需格式”

有人可以帮忙吗?

我的数据集

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

所需格式

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

编辑 - 完整代码

我在评论中建议进行更改,并添加了“j = json.loads(JsonData)”

我现在收到一个错误:

“googleapiclient.errors.HttpError:<HttpError 400 请求https://sheets.googleapis.com/v4/spreadsheets//values/sheet1%21A1?valueInputOption=USER_ENTERED&alt=json返回“收到的 JSON 负载无效。“data.values”中的未知名称“FMX 令牌”:找不到字段。”

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: Intu0021) {n tokens(first: 500, skip: $skip) {n namen symboln}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()

回答

这很简单:

result = [[token['name'], token['symbol']] for token in data['data']['tokens']]


以上是JSON到Python列表的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>