前提
Google Spread Sheet APIを使用しています。
各行の内容を配列に格納,ソート後、
特定のキー,階層に編集後、JSONファイルとして出力するスクリプトを作ろうとしています。
しかし下記にあるように、想定していたものとは違う形式のJSONファイルが出力されてしまいます。
どうすれば解決するでしょうか。
実現したいこと
- 配列の内容を、各行ごとのデータに分割させた状態で、JSONファイルに出力させる
(該当行:33~43行目)
発生している問題・エラーメッセージ
- 期待している出力結果
py
1{ 2 "value": "テスト項目", 3 "image": { 4 "sourceUri": "https://*****" 5 } 6}, 7{ 8 "value": "テスト項目2", 9 "image": { 10 "sourceUri": "https://*****" 11 } 12}, 13# ~~~~~以下、同様の階層が続く
- 実際の出力結果
value:
配列の内容が一気に出力されてしまう(['aaa'], ['bbb'], といったように、各行の内容が1行にまとまってしまう)
sourceUrl:
本来は1つのカッコ内に1つのみ要素が入るところが、複数個要素が配置されてしまっている
該当のソースコード
py
1import gspread 2import json 3from oauth2client.service_account import ServiceAccountCredentials 4 5SHEET_ID = "*****" 6GCPKEY = "key.json" 7JSON_EXP = "avatarsInfo.json" 8 9 10def connect_gspread(jsonf, key): 11 scope = ['https://spreadsheets.google.com/feeds', 12 'https://www.googleapis.com/auth/drive'] 13 credentials = ServiceAccountCredentials.from_json_keyfile_name( 14 jsonf, scope) 15 gc = gspread.authorize(credentials) 16 SPREADSHEET_KEY = key 17 worksheet = gc.open_by_key(SPREADSHEET_KEY).sheet1 18 return worksheet 19 20 21ws = connect_gspread(GCPKEY, SHEET_ID) 22 23# 範囲定義 24avatarNames_JA = ws.get_values("A:A") 25avatarNames_EN = ws.get_values("B:B") 26avatarImageUrl = ws.get_values("F:F") 27 28# 一括ソート 29zip_lists = zip(avatarNames_JA, avatarNames_EN, avatarImageUrl) 30zip_sort = sorted(zip_lists) 31avatarNames_JA, avatarNames_EN, avatarImageUrl = zip(*zip_sort) 32 33json_dict = { 34 "value": f'{avatarNames_JA}({avatarNames_EN})', 35 "image": { 36 "sourceUri": avatarImageUrl 37 } 38} 39 40# JSON生成 41with open(JSON_EXP, "w")as f: 42 json.dump(json_dict, f, indent=4) 43
試したこと
Read & write cell values - Google Developers
https://developers.google.com/sheets/api/guides/values
Python から JSON へ変換 - やさしいPython入門
https://python.softmoco.com/basics/python-json-dump.php
補足情報(FW/ツールのバージョンなど)
Visual Studio Code 1.74.3
python 3.11(Microsoft Store)
Google SpreadSheet API

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2023/01/27 15:37
2023/01/27 15:50 編集
2023/01/27 15:57