The JSON and Python dicts are mapped as follows:
JSON | Python |
---|---|
object | dict |
array | list |
string | unicode |
number (int) | int, long |
number(real) | float |
true | True |
false | False |
null | None |
Therefore, if you parse JSON with json.loads ()
and register it with dynamo.put_item ()
as it is, it will be registered with the above type. At this time, if there is a float type, it gets angry as follows.
Float types are not supported. Use Decimal types instead.
Python floats cannot be registered in DynamoDB as they are. You need to register with Decimal instead.
Float needs to be mapped to Decimal. For example, suppose the following data is registered.
json_data
{"Timestamp": "20160323T203501.000+0900", "x": -0.279938, "y": -0.754028, "z": -0.607758 }
When parsing JSON, add parse_float = decimal.Decimal
as shown below.
import json
import boto3
import decimal
#...abridgement
item = json.loads(json_data, parse_float=decimal.Decimal)
dynamo = boto3.resource('dynamodb').Table('ThisIsJustTest')
dynamo.put_item(Item = item)
It was mentioned in the Python official, but I didn't get any information right away, so I wrote it as an article.
https://docs.python.org/2/library/json.html#encoders-and-decoders
parse_float, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal).
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
It was also smooth in the AWS documentation. https://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/gettingstartedguide/GettingStarted.Python.02.html
The following methods are introduced.
https://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/gettingstartedguide/GettingStarted.Python.03.html http://stackoverflow.com/questions/1960516/python-json-serialize-a-decimal-object
Recommended Posts