0

my dict output looks like this enter image description here

What library to use to convert it to json in python?

edit 1: my code now looks like

import boto3
import json
rds_client = boto3.client('rds', 'ap-southeast-1')
db_instance_info = rds_client.describe_db_instances()
with open('result.json', 'w') as db:
    json.dump(db_instance_info, db)

and it shows this error

Traceback (most recent call last):
  File "list.py", line 14, in <module>
    json.dump(db_instance_info, db)
  File "/usr/lib/python2.7/json/__init__.py", line 189, in dump
    for chunk in iterable:
  File "/usr/lib/python2.7/json/encoder.py", line 434, in _iterencode
    for chunk in _iterencode_dict(o, _current_indent_level):
  File "/usr/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "/usr/lib/python2.7/json/encoder.py", line 332, in _iterencode_list
    for chunk in chunks:
  File "/usr/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "/usr/lib/python2.7/json/encoder.py", line 442, in _iterencode
    o = _default(o)
  File "/usr/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2017, 6, 6, 9, 7, 33, 472000, tzinfo=tzutc()) is not JSON serializable
Proteeti Prova
  • 1,079
  • 4
  • 25
  • 49

3 Answers3

1

The error is explicit:

TypeError: datetime.datetime(2017, 6, 6, 9, 7, 33, 472000, tzinfo=tzutc()) is not JSON serializable

By default the json module cannot serialize any of the types from the datetime module, and your dictionary contains ..., u'InstanceCreateTime': datetime.datetime(2017, 6, 6, 9, 7, 33, 472000, tzinfo=tzutc()), and other datetimes later.

The idiomatic way is to define a custom encoder to process the relevant objects. It is enough to override the default method, process the specific objects and pass everything else to the base class method:

class DateEncoder(json.JSONEncoder):
"""This encoder only use the default string convertion for the types
date, time and datetime of the datetime module"""
    def default(self, o):
        if (isinstance(o, datetime.date)
            or isinstance(o, datetime.datetime)
            or isinstance(o, datetime.time)):
            return str(o)                # specialize here the format...
        return json.JSONEncoder.default(self, o)

You can then use it to build your json:

with open('result.json', 'w') as db:
    json.dump(db_instance_info, db, cls=DateEncoder)
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

Just use the json module:

import json
jsonarray = json.dumps(the_dict, ensure_ascii=False)

The ensure_ascii bit is there to avoid any encoding/decoding errors.

Adi219
  • 4,712
  • 2
  • 20
  • 43
0

You can use the json library in python

import json
x = {'s': True}
r = json.dumps(x)

This will give a json string

rennerj2
  • 76
  • 8