teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

JSONファイル変数の内容を確認するためのスクリプトを追記

2020/12/01 02:08

投稿

unity_level1
unity_level1

スコア8

title CHANGED
File without changes
body CHANGED
@@ -3,6 +3,10 @@
3
3
  現状、エラーの検討が付かないため、大変お手数ですが、お分かりになる方がおりましたら、ご教示いただけますと幸いです。
4
4
  ※GoogleDriveから以外でも実現できる方法がございましたらご教示いただけますと非常に助かります。
5
5
 
6
+ **追記内容**
7
+ 2020/12/01
8
+ エラーログの追記
9
+ スクリプトの修正(def get_tweet_content(json_file_path)以下に追記)
6
10
 
7
11
  ### 実行環境
8
12
  ■Google Colaboratory
@@ -88,9 +92,19 @@
88
92
  #テキストファイルを読み込む
89
93
  file = open(json_file_path, 'r', encoding='utf-8')
90
94
  #開いたファイルをjson.load関数でJSONとして読み込む
91
- json_data = json.load(file)
95
+ #json_data = json.load(file) <-------テストの際に不要のためコメントアウトしている
92
96
  #JSONとして読み込んだfile変数が格納されたjson_data変数に、jsonデータを格納
93
97
  #random.choice()でリストからランダムに要素を一つ取得
98
+
99
+ ##下記追記スクリプト
100
+ #JSONとして読み込んだfile変数が格納されたjson_data変数に、jsonデータを格納
101
+ try:
102
+ json_data = json.load(file)
103
+ except json.JSONDecodeError as e:
104
+ print(str(e))
105
+ print(e.doc)
106
+ exit(0)
107
+
94
108
  return random.choice(json_data["contents"])
95
109
 
96
110
 
@@ -182,7 +196,51 @@
182
196
 
183
197
 
184
198
 
199
+ ### 追記のエラーログ
200
+ Extra data: line 1 column 11 (char 10)
201
+ "contents":[
202
+ {
203
+ "img_url":"https://drive.google.com/file/d/ファイルID/view?usp=sharing",
204
+ "tweet_text":"ファイル名"
205
+
206
+ },
207
+ {
208
+ "img_url":"https://drive.google.com/file/d/ファイルID/view?usp=sharing",
209
+ "tweet_text":"ファイル名"
210
+ },
211
+ {
212
+ "img_url":"https://drive.google.com/file/d/ファイルID/view?usp=sharing",
213
+ "tweet_text":"ファイル名"
214
+ },
215
+ {
216
+ "img_url":"https://drive.google.com/file/d/ファイルID/view?usp=sharing",
217
+ "tweet_text":"ファイル名"
218
+ }
219
+ ]
220
+ }
221
+ ---------------------------------------------------------------------------
222
+ UnboundLocalError Traceback (most recent call last)
223
+ <ipython-input-14-0f1ead28e8c2> in <module>()
224
+ 1 if __name__ == '__main__':
225
+ ----> 2 main()
185
226
 
227
+ 1 frames
228
+ <ipython-input-13-37b9a2f30b06> in main()
229
+ 1 def main():
230
+ 2 json_file_path = 'tweetcontent.jsonのファイルパス'
231
+ ----> 3 tweet_content = get_tweet_content(json_file_path)
232
+ 4 media_id = upload_media(tweet_content['img_url'])
233
+ 5 post_tweet(tweet_content['tweet_text'], media_id)
234
+
235
+ <ipython-input-10-bb7332d3f4d2> in get_tweet_content(json_file_path)
236
+ 15 exit(0)
237
+ 16
238
+ ---> 17 return random.choice(json_data["contents"])
239
+
240
+ UnboundLocalError: local variable 'json_data' referenced before assignment
241
+
242
+
243
+
186
244
  ### 参照リンク
187
245
  [PythonとJSONで画像付きツイートを自動化する](https://note.com/rottenmarron/n/n09463b5988e3)
188
246