def load_project_data(project_name):
"""
Load project data from properties file
"""
global identity_domain
global username
global image_name
global os_project_name
global os_image_name
data_type = "project"
identity_domain = orchestration_helper.get_config_item(project_name, project_name, 'identity_domain', data_type)
username = orchestration_helper.get_config_item(project_name, project_name, 'username', data_type)
image_name = orchestration_helper.get_config_item(project_name, project_name, 'image_name', data_type)
os_project_name = orchestration_helper.get_config_item(project_name, project_name, 'openstack_project', data_type)
os_image_name = orchestration_helper.get_config_item(project_name, project_name, 'openstack_image_name', data_type)
projdata = {'opc': {'Domain': identity_domain, 'username': username, 'image': image_name}, 'openstack': {'os_project_name': os_project_name, 'os_image_name': os_image_name}}
return (json.JSONEncoder().encode(projdata))
python类JSONEncoder()的实例源码
def format_list(json_list, columns, args, options):
format = options.format
formatter = None
if format == "raw_json":
output(json_list)
return
elif format == "pretty_json":
enc = json.JSONEncoder(False, False, True, True, True, 2)
output(enc.encode(json.loads(json_list)))
return
else:
formatter = FORMATS[format]
assert_usage(formatter != None,
"Format {0} not recognised".format(format))
formatter_instance = formatter(columns, args, options)
formatter_instance.display(json_list)
def default(self, object):
try:
iterable = iter(object)
except TypeError:
pass
else:
return list(iterable)
try:
properties = object.__dict__
except AttributeError:
pass
else:
return dict((key, value) for key, value in properties.items() if not key.startswith('_'))
return JSONEncoder.default(self, object)
def test_adapt_dumps(self):
from psycopg2.extras import json, Json
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
curs = self.conn.cursor()
obj = Decimal('123.45')
def dumps(obj):
return json.dumps(obj, cls=DecimalEncoder)
self.assertEqual(curs.mogrify("%s", (Json(obj, dumps=dumps),)),
b"'123.45'")
def test_adapt_subclass(self):
from psycopg2.extras import json, Json
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
class MyJson(Json):
def dumps(self, obj):
return json.dumps(obj, cls=DecimalEncoder)
curs = self.conn.cursor()
obj = Decimal('123.45')
self.assertEqual(curs.mogrify("%s", (MyJson(obj),)), b"'123.45'")
def default(self, obj):
if isinstance(obj.__class__, DeclarativeMeta):
# an SQLAlchemy class
fields = {}
for field in [x for x in dir(obj) if not x.startswith('_')
and x != 'metadata' and x != '_sa_instance_state']:
data = obj.__getattribute__(field)
if isinstance(data, types.MethodType):
continue
try:
json.dumps(data) # this will fail on non-encodable values, like other classes
fields[field] = data
except TypeError:
try:
fields[field] = [str(d) for d in data]
except:
fields[field] = None
except UnicodeEncodeError:
fields[field] = 'Non-encodable'
# a json-encodable dict
return fields
return json.JSONEncoder.default(self, obj)
def default(self, obj):
if hasattr(obj, '__json__'):
return obj.__json__()
return json.JSONEncoder.default(self, obj)
def default(self, obj):
if isinstance(obj, Type):
return obj.serialize()
return json.JSONEncoder.default(self, obj)
def default(self, obj):
if isinstance(obj, np.ndarray) and obj.ndim == 1:
return obj.tolist()
elif isinstance(obj, np.generic):
return obj.item()
return json.JSONEncoder.default(self, obj)
def default(self, obj):
if isinstance(obj, frozendict):
return dict(obj)
return json.JSONEncoder.default(self, obj)
def default(self, obj):
if isinstance(obj, ndarray):
return obj.tolist()
elif isinstance(obj, bytes):
return obj.decode()
else:
return json.JSONEncoder.default(self, obj)
# this replaces the default encoder and makes it so Tornado will do the right
# thing when it converts dicts to JSON when a
# tornado.web.RequestHandler.write(dict) is called.
def simplify(self, precision):
return self.segments(precision)
# overwrite JSONEncoder for svg classes which have defined a .json() method
def default(self, obj):
if not isinstance(obj, tuple(svgClass.values() + [Svg])):
return json.JSONEncoder.default(self, obj)
if not hasattr(obj, 'json'):
return repr(obj)
return obj.json()
# Code executed on module load #
# SVG tag handler classes are initialized here
# (classes must be defined before)
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self, obj)
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self, obj)
def default(self, obj):
if type(obj) in self.addedtypes:
return self.addedtypes[type(obj)].encode(obj)
return json.JSONEncoder.default(self, obj)
def default(self, obj):
if isinstance(obj, smallDuck):
return { obj.__class__.__name__ : obj.__dict__ }
return json.JSONEncoder.default(self, obj)
def search(request):
current_username=request.POST.get('username')
try:
user=User.objects.get(username=current_username)
python_object = {'flag':'True',
'userName': user.username,
'first_name': user.first_name,
'last_name': user.last_name}
except Exception as e:
python_object = {'flag':'False'}
datatosend=json.JSONEncoder().encode(python_object)
return HttpResponse(datatosend)
#views for save_settings table
def add_friends(request):
current_username = request.POST.get('username')
current_friendList = request.POST.get('friendList')
try:
username=User.objects.get(username=current_username)
except Exception as e:
python_object = {'status':'203'}
datatosend=json.JSONEncoder().encode(python_object)
return HttpResponse(datatosend)
json_obj = json.loads(current_friendList)
ol=[]
try:
existingUser = FriendList.objects.get(user__username = username)
user_friends = existingUser.getfoo()
for c in user_friends:
c = unicodedata.normalize('NFKD', c).encode('ascii','ignore')
# print type(c)
ol.append(c)
for c in json_obj:
c = unicodedata.normalize('NFKD', c).encode('ascii','ignore')
ol.append(c)
existingUser.friendList = json.dumps(ol)
existingUser.save()
python_object = {'status':'200'}
except:
friend = FriendList(user = username)
friend.setfoo(current_friendList)
friend.save()
python_object = {'status':'200'}
datatosend=json.JSONEncoder().encode(python_object)
return HttpResponse(datatosend)
def default(self, obj):
"""Converts an ndarray into a dictionary for efficient serialization.
The dict has three keys:
- dtype : The datatype of the array as a string.
- shape : The shape of the array as a tuple.
- __ndarray__ : The data of the array as a list.
Parameters
----------
obj : :obj:`numpy.ndarray`
The ndarray to encode.
Returns
-------
:obj:`dict`
The dictionary serialization of obj.
Raises
------
TypeError
If obj isn't an ndarray.
"""
if isinstance(obj, np.ndarray):
return dict(__ndarray__=obj.tolist(),
dtype=str(obj.dtype),
shape=obj.shape)
# Let the base class default method raise the TypeError
return _json.JSONEncoder(self, obj)