
AWS DynamoDBに下記のような問題データを書き込みたいと考えています。
問題データは100問ほどありますが、必ずしも画像を必要としないため、image_urlがあるものとないものが混在します。
(questionList.json)
JSON
1{ 2 "q_id" : "001", 3 "q_body" : "日本の首都はどこか。", 4 "q_answer" : "東京", 5 "image_url" : "/tokyo.jpg", 6 "keywords" : [ 7 "日本", 8 "東京" 9 ] 10 }, 11 { 12 "q_id" : "002", 13 "q_body" : "アメリカの首都はどこか。", 14 "q_answer" : "ワシントンD.C", 15 "image_url" : "", 16 "keywords" : [ 17 "アメリカ", 18 "ワシントンD.C." 19 ] 20 },
書き込みテスト段階なので、書き込み先のDynamodbは本番環境ではなく、serverlessフレームワークのserverless-dynamodb-localプラグインを使用したlocalhost:8000に用意しています。
上記のJSONデータをこのDynamodbに書き込むために、Boto3(AWS SDK for Python)で下記のようなコードを記述しました。
(questionListLoad.py)
Python
1from __future__ import print_function 2import boto3 3import codecs 4import json 5 6dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-1', endpoint_url="http://localhost:8000") 7 8table = dynamodb.Table('questionListTable') 9 10with open("questionList.json", "r", encoding='utf-8_sig') as json_file: 11 items = json.load(json_file) 12 for item in items: 13 q_id = item['q_id'] 14 q_body = item['q_body'] 15 q_answer = item['q_answer'] 16 image_url = item['image_url'] 17 keywords = item['keywords'] 18 19 print("Adding detail:", q_id, q_body) 20 21 table.put_item( 22 Item={ 23 'q_id': q_id, 24 'q_body': q_body, 25 'q_answer': q_answer, 26 'image_url': image_url, 27 'keywords': keywords, 28 } 29 )
このコードを実行すると、空文字の部分で下記のようなエラーが発生します。
botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the PutItem operation: One or more parameter values were invalid: An AttributeValue may not contain an empty string
どうやらJSONの空文字が原因のようです。
試しに空文字を含むimage_urlを下記のように書き込み対象から外すと、問題なく書き込みが完了しました。
Python
1with open("questionList.json", "r", encoding='utf-8_sig') as json_file: 2 details = json.load(json_file) 3 for detail in details: 4 q_id = detail['q_id'] 5 q_body = detail['q_body'] 6 q_answer = detail['q_answer'] 7 #image_url = detail['image_url'] 8 keywords = detail['keywords'] 9 10 print("Adding detail:", q_id, q_body) 11 12 table.put_item( 13 Item={ 14 'q_id': q_id, 15 'q_body': q_body, 16 'q_answer': q_answer, 17 #'image_url': image_url, 18 'keywords': keywords, 19 } 20 )
DynamoDBはNoSQLなので、特性を活かした上手な方法が他にあるかも知れませんが、上記のようなデータを空文字を無視して書き込むためには、どのようにコードを修正すればよいでしょうか。「もしimage_urlが存在するなら書き込む。なければ無視する」ということがしたいです。
よろしくお願いします。

回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/08/18 04:27