Here are the examples of how to json in python. These are taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
132 Examples
3
File: user_main.py, Project: allura, View licenseuses: allura.lib.plugin.AuthenticationProvider.get
def __json__(self):
auth_provider = AuthenticationProvider.get(request)
return dict(
username=self.user.username,
name=self.user.display_name,
joined=auth_provider.user_registration_date(self.user),
localization=self.user.get_pref('localization')._deinstrument(),
sex=self.user.get_pref('sex'),
telnumbers=self.user.get_pref('telnumbers')._deinstrument(),
skypeaccount=self.user.get_pref('skypeaccount'),
webpages=self.user.get_pref('webpages')._deinstrument(),
availability=self.user.get_pref('availability')._deinstrument())
3
File: geometry.py, Project: theyworkforyou, View licenseuses: django.contrib.gis.geos.base.gdal.GEOJSON
@property
def json(self):
"""
Returns GeoJSON representation of this Geometry if GDAL 1.5+
is installed.
"""
if gdal.GEOJSON:
return self.ogr.json
else:
raise GEOSException('GeoJSON output only supported on GDAL 1.5+.')
3
File: wrappers.py, Project: ReproWeb, View licenseuses: werkzeug.exceptions.BadRequest
@cached_property
def json(self):
"""Get the result of simplejson.loads if possible."""
if 'json' not in self.environ.get('CONTENT_TYPE', ''):
raise BadRequest('Not a JSON request')
try:
return loads(self.data)
except Exception:
raise BadRequest('Unable to read JSON request')
3
File: models.py, Project: geonode, View licenseuses: geonode.utils.num_encode
def json(self):
return {
"map": self.map.id,
"created": self.created_dttm.isoformat(),
"user": self.user.username if self.user else None,
"url": num_encode(self.id)
}
3
File: baremodels.py, Project: dissemin, View licenseuses: papers.utils.remove_nones
def json(self):
"""
JSON representation of the paper, for dataset dumping purposes
"""
return remove_nones({
'title': self.title,
'type': self.doctype,
'date': self.pubdate.isoformat(),
'authors': [a.json() for a in self.authors],
'records': [r.json() for r in self.oairecords],
'pdf_url': self.pdf_url,
'classification': self.oa_status,
})
3
File: geometries.py, Project: django-nonrel, View licenseuses: django.contrib.gis.gdal.prototypes.capi.to_json
@property
def json(self):
"""
Returns the GeoJSON representation of this Geometry (requires
GDAL 1.5+).
"""
if GEOJSON:
return capi.to_json(self.ptr)
else:
raise NotImplementedError('GeoJSON output only supported on GDAL 1.5+.')
3
File: webhook.py, Project: allura, View licenseuses: allura.lib.h.absurl
def __json__(self):
return {
'_id': unicode(self._id),
'url': h.absurl(u'/rest' + self.url()),
'type': unicode(self.type),
'hook_url': unicode(self.hook_url),
'mod_date': self.mod_date,
}
3
File: models.py, Project: glottolog3, View licenseuses: clld.db.models.common.IdentifierType.iso.value
def __json__(self, req=None, core=False):
def ancestor(l):
r = {"name": l.name, "id": l.id}
if req:
r['url'] = req.resource_url(l)
return r
res = super(Languoid, self).__json__(req)
if not core:
res['classification'] = [ancestor(l) for l in reversed(list(self.get_ancestors()))]
if self.iso_code:
res[IdentifierType.iso.value] = self.iso_code
res['macroareas'] = {ma.id: ma.name for ma in self.macroareas}
return res
3
File: models.py, Project: RedFlash, View licenseuses: django.utils.simplejson.dumps
def json(self):
""" Create a JSON representation of this objects with the
fields named in the _SERIALIZED_FIELDS_ list. """
repr = {}
for f in self._SERIALIZED_FIELDS_:
repr[f] = getattr(self, f)
return simplejson.dumps(repr)
3
File: navigation.py, Project: plugin.video.pulsar, View licenseuses: xbmcgui.ListItem
def _json(url):
with closing(urllib2.urlopen(url)) as response:
if response.code >= 300 and response.code <= 307:
item = xbmcgui.ListItem(path=response.geturl(), thumbnailImage=xbmc.getInfoLabel("ListItem.Art(thumb)"))
xbmcplugin.setResolvedUrl(HANDLE, True, item)
return
payload = response.read()
if payload:
return json.loads(payload)
3
File: http.py, Project: streamlink, View licenseuses: requests.Request
def __json__(self):
method = self.args.get("method", "GET")
req = requests.Request(method=method, **valid_args(self.args))
# prepare_request is only available in requests 2.0+
if hasattr(self.session.http, "prepare_request"):
req = self.session.http.prepare_request(req)
else:
req = req.prepare()
headers = dict(map(normalize_key, req.headers.items()))
return dict(type=type(self).shortname(), url=req.url,
method=req.method, headers=headers,
body=req.body)
3
File: asserts.py, Project: attest, View licenseuses: attest.Assert
@suite.test
def json():
"""Assert.json"""
Assert('{"works": true}').json == dict(works=True)
Assert('{"works": true}').json != dict(works=False)
with Assert.raises(AssertionError):
Assert('{"works": true}').json != dict(works=True)
with Assert.raises(AssertionError):
Assert('{"works": true}').json == dict(works=False)
3
File: storing_test.py, Project: tushare, View licenseuses: tushare.get_hist_data
def json():
df = ts.get_hist_data('000875')
df.to_json('c:/day/000875.json',orient='records')
#或者直接使用
print(df.to_json(orient='records'))
3
File: artifact.py, Project: allura, View licenseuses: allura.lib.h.absurl
def __json__(self, posts_limit=None, is_export=False):
"""Return a JSON-encodable :class:`dict` representation of this
Artifact.
"""
return dict(
_id=str(self._id),
mod_date=self.mod_date,
labels=list(self.labels),
related_artifacts=[a.url() for a in self.related_artifacts()],
discussion_thread=self.discussion_thread.__json__(limit=posts_limit, is_export=is_export),
discussion_thread_url=h.absurl('/rest%s' %
self.discussion_thread.url()),
)
3
File: ustreamtv.py, Project: streamlink, View licenseuses: streamlink.stream.Stream.__json__
def __json__(self):
json = Stream.__json__(self)
json.update({
"channel_id": self.channel_id,
"page_url": self.page_url,
"provider": self.provider,
"stream_index": self.stream_index,
"password": self.password
})
return json
3
File: auth.py, Project: allura, View licenseuses: allura.lib.h.absurl
def __json__(self):
return dict(
username=self.username,
name=self.display_name,
url=h.absurl(self.url()),
)
3
File: discuss.py, Project: allura, View licenseuses: allura.lib.h.absurl
def __json__(self, limit=None, page=None, is_export=False):
return dict(
_id=self._id,
discussion_id=str(self.discussion_id),
subject=self.subject,
limit=limit,
page=page,
posts=[dict(slug=p.slug,
text=p.text,
subject=p.subject,
author=p.author().username,
author_icon_url=h.absurl(p.author().icon_url()),
timestamp=p.timestamp,
last_edited=p.last_edit_date,
attachments=self.attachment_for_export(p) if is_export else self.attachemtns_for_json(p))
for p in self.query_posts(status='ok', style='chronological', limit=limit, page=page)
]
)
3
File: dump_manage.py, Project: acousticbrainz-server, View licenseuses: config.SQLALCHEMY_DATABASE_URI
@cli.command()
@click.option("--location", "-l", default=os.path.join(os.getcwd(), 'export'), show_default=True,
help="Directory where dumps need to be created")
@click.option("--rotate", "-r", is_flag=True)
@click.option("--no-lowlevel", "-nl", is_flag=True, help="Don't dump low-level data.")
@click.option("--no-highlevel", "-nh", is_flag=True, help="Don't dump high-level data.")
def json(location, rotate, no_lowlevel, no_highlevel):
db.init_db_engine(config.SQLALCHEMY_DATABASE_URI)
if no_lowlevel and no_highlevel:
print("wut? check your options, mate!")
if not no_lowlevel:
_json_lowlevel(location, rotate)
if not no_highlevel:
_json_highlevel(location, rotate)
3
File: lib.py, Project: ocf, View licenseuses: foam.geni.db.GeniDB.getSliverData
def __json__ (self):
data = self.getDataDict(True)
if self.__urn:
dbdata = GeniDB.getSliverData(self.__urn, False)
data.update(dbdata)
return data
3
File: requests.py, Project: pyjs, View licenseuses: flask.helpers._assert_have_json
@cached_property
def json(self):
"""If the mimetype is `application/json` or `application/json-rpc`
this will contain the parsed JSON data. Otherwise this will be `None`.
This requires Python 2.6 or an installed version of simplejson.
"""
if __debug__:
_assert_have_json()
if self.mimetype in ['application/json', 'application/json-rpc']:
request_charset = self.mimetype_params.get('charset')
try:
if request_charset is not None:
return json.loads(self.data, encoding=request_charset)
return json.loads(self.data)
except ValueError as E:
return self.on_json_loading_failed(E)
3
File: Result.py, Project: coala, View licenseuses: coala_utils.decorators.get_public_members
def __json__(self, use_relpath=False):
_dict = get_public_members(self)
if use_relpath and _dict['diffs']:
_dict['diffs'] = {relpath(file): diff
for file, diff in _dict['diffs'].items()}
_dict['aspect'] = self.aspect.__qualname__
return _dict
3
File: serializers.py, Project: termite-data-server, View licenseuses: gluon.contrib.simplejson.dumps.replace.replace
def json(value, default=custom_json):
# replace JavaScript incompatible spacing
# http://timelessrepo.com/json-isnt-a-javascript-subset
return json_parser.dumps(value,
default=default).replace(ur'\u2028',
'\\u2028').replace(ur'\2029',
'\\u2029')
3
File: blog.py, Project: allura, View licenseuses: allura.lib.h.absurl
def __json__(self, posts_limit=None, is_export=False):
return dict(super(BlogPost, self).__json__(posts_limit=posts_limit, is_export=is_export),
author=self.author().username,
title=self.title,
url=h.absurl('/rest' + self.url()),
text=self.text,
labels=list(self.labels),
state=self.state)
3
File: validator.py, Project: nudge, View licenseuses: nudge.json.json_decode
def Json():
def f(s):
try:
return nudge.json.json_decode(s)
except (ValueError), e:
raise ValidationError("must be valid json")
return f
3
File: views.py, Project: otm-legacy, View licenseuses: django.core.serializers.serialize
def json(self, context, context_instance):
"""
Given some context variables, this method returns a JSON representation
of those variables.
"""
data = serializers.serialize('json', [context['favorite']])
return HttpResponse(data, content_type='application/json')
3
File: Bear.py, Project: coala, View licenseuses: coala_utils.decorators.get_public_members.items
@classmethod
def __json__(cls):
"""
Override JSON export of ``Bear`` object.
"""
# json cannot serialize properties, so drop them
_dict = {key: value for key, value in get_public_members(cls).items()
if not isinstance(value, property)}
metadata = cls.get_metadata()
non_optional_params = metadata.non_optional_params
optional_params = metadata.optional_params
_dict["metadata"] = {
"desc": metadata.desc,
"non_optional_params": ({param: non_optional_params[param][0]}
for param in non_optional_params),
"optional_params": ({param: optional_params[param][0]}
for param in optional_params)}
return _dict
3
File: unknown.py, Project: exabgp, View licenseuses: exabgp.bgp.message.open.capability.capability.Capability.CODE.reserved
def json (self):
if self.capability in Capability.CODE.reserved:
iana = 'reserved'
elif self.capability in Capability.CODE.unassigned:
iana = 'unassigned'
else:
iana = 'unknown'
return '{ "name": "unknown", "iana": "%s", "value": %d, "raw": "%s" }' % (iana,self.capability,self.data)
3
File: metadata_api.py, Project: starter-pack, View licenseuses: datetime.timezone.utc
@cache
def json(self, repo, last_timestamp=None, last_json=None):
"""Return JSON payload, or None if not modified since timestamp."""
url = 'https://api.github.com/repos/{}/releases/latest'.format(repo)
header = {'If-Modified-Since': datetime.datetime.fromtimestamp(
last_timestamp, datetime.timezone.utc).strftime(
'%a, %d %b %Y %H:%M:%S GMT')}
req = get_ok(url, auth=get_auth(), headers=header)
if req.status_code == 304:
return last_json
resp = req.json()
assets = [r['browser_download_url'] for r in resp['assets']]
return {'version': resp['tag_name'].strip(),
'published_at': resp['published_at'],
'assets': best_asset(assets),
'zipball_url': resp['zipball_url']}
3
File: graph.py, Project: reprozip, View licenseuses: reprounzip.utils.unicode_
def json(self, level_pkgs):
if level_pkgs == LVL_PKG_PACKAGE:
logging.critical("JSON output doesn't support --packages package")
sys.exit(1)
elif level_pkgs == LVL_PKG_FILE:
files = sorted(unicode_(f) for f in self.files)
else:
assert False
return {'name': self.name, 'version': self.version or None,
'files': files}
2
File: odoo.py, Project: odoorpc, View licenseuses: odoorpc.error.RPCError
def json(self, url, params):
"""Low level method to execute JSON queries.
It basically performs a request and raises an
:class:`odoorpc.error.RPCError` exception if the response contains
an error.
You have to know the names of each parameter required by the function
called, and set them in the `params` dictionary.
Here an authentication request:
.. doctest::
:options: +SKIP
>>> data = odoo.json(
... '/web/session/authenticate',
... {'db': 'db_name', 'login': 'admin', 'password': 'admin'})
>>> from pprint import pprint
>>> pprint(data)
{'id': 645674382,
'jsonrpc': '2.0',
'result': {'db': 'db_name',
'session_id': 'fa740abcb91784b8f4750c5c5b14da3fcc782d11',
'uid': 1,
'user_context': {'lang': 'en_US',
'tz': 'Europe/Brussels',
'uid': 1},
'username': 'admin'}}
.. doctest::
:hide:
>>> data = odoo.json(
... '/web/session/authenticate',
... {'db': DB, 'login': USER, 'password': PWD})
>>> data['result']['db'] == DB
True
>>> data['result']['uid'] == 1
True
>>> data['result']['username'] == USER
True
And a call to the ``read`` method of the ``res.users`` model:
>>> data = odoo.json(
... '/web/dataset/call',
... {'model': 'res.users', 'method': 'read',
... 'args': [[1], ['name']]})
>>> from pprint import pprint
>>> pprint(data)
{'id': ...,
'jsonrpc': '2.0',
'result': [{'id': 1, 'name': 'Administrator'}]}
*Python 2:*
:return: a dictionary (JSON response)
:raise: :class:`odoorpc.error.RPCError`
:raise: `urllib2.HTTPError` (if `params` is not a dictionary)
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:return: a dictionary (JSON response)
:raise: :class:`odoorpc.error.RPCError`
:raise: `urllib.error.HTTPError` (if `params` is not a dictionary)
:raise: `urllib.error.URLError` (connection error)
"""
data = self._connector.proxy_json(url, params)
if data.get('error'):
raise error.RPCError(
data['error']['data']['message'],
data['error'])
return data
0
File: base.py, Project: vj4, View licenseuses: vj4.util.json.encode
def json(self, obj):
self.response.content_type = 'application/json'
self.response.headers.add('Cache-Control', 'no-store, no-cache, must-revalidate')
self.response.text = json.encode(obj)
0
File: argonauts.py, Project: django-argonauts, View licenseuses: argonauts.json_dumps
@register.filter
def json(a):
"""
Output the json encoding of its argument.
This will escape all the HTML/XML special characters with their unicode
escapes, so it is safe to be output anywhere except for inside a tag
attribute.
If the output needs to be put in an attribute, entitize the output of this
filter.
"""
json_str = json_dumps(a)
# Escape all the XML/HTML special characters.
escapes = ['<', '>', '&']
for c in escapes:
json_str = json_str.replace(c, r'\u%04x' % ord(c))
# now it's safe to use mark_safe
return mark_safe(json_str)
0
File: models.py, Project: geonode, View licenseuses: geonode.layers.models.Layer.objects.get
def json(self, layer_filter):
"""
Get a JSON representation of this map suitable for sending to geoserver
for creating a download of all layers
"""
map_layers = MapLayer.objects.filter(map=self.id)
layers = []
for map_layer in map_layers:
if map_layer.local:
layer = Layer.objects.get(typename=map_layer.name)
layers.append(layer)
else:
pass
if layer_filter:
layers = [l for l in layers if layer_filter(l)]
# the readme text will appear in a README file in the zip
readme = (
"Title: %s\n" +
"Author: %s\n" +
"Abstract: %s\n"
) % (self.title, self.poc, self.abstract)
if self.license:
readme += "License: %s" % self.license
if self.license.url:
readme += " (%s)" % self.license.url
readme += "\n"
if self.constraints_other:
readme += "Additional constraints: %s\n" % self.constraints_other
def layer_json(lyr):
return {
"name": lyr.typename,
"service": lyr.service_type,
"serviceURL": "",
"metadataURL": ""
}
map_config = {
# the title must be provided and is used for the zip file name
"map": {"readme": readme, "title": self.title},
"layers": [layer_json(lyr) for lyr in layers]
}
return json.dumps(map_config)
0
File: response.py, Project: gns3-server, View licenseuses: aiohttp.web.HTTPBadRequest
def json(self, answer):
"""
Set the response content type to application/json and serialize
the content.
:param anwser The response as a Python object
"""
self.content_type = "application/json"
if hasattr(answer, '__json__'):
answer = answer.__json__()
elif isinstance(answer, list):
newanswer = []
for elem in answer:
if hasattr(elem, '__json__'):
elem = elem.__json__()
newanswer.append(elem)
answer = newanswer
if self._output_schema is not None:
try:
jsonschema.validate(answer, self._output_schema)
except jsonschema.ValidationError as e:
log.error("Invalid output query. JSON schema error: {}".format(e.message))
raise aiohttp.web.HTTPBadRequest(text="{}".format(e))
self.body = json.dumps(answer, indent=4, sort_keys=True).encode('utf-8')
0
File: s3export.py, Project: eden, View licenseuses: gluon.serializers.jsons
def json(self, resource,
start=None,
limit=None,
fields=None,
orderby=None,
represent=False,
tooltip=None):
"""
Export a resource as JSON
@param resource: the resource to export from
@param start: index of the first record to export
@param limit: maximum number of records to export
@param fields: list of field selectors for fields to include in
the export (None for all fields)
@param orderby: ORDERBY expression
@param represent: whether values should be represented
@param tooltip: additional tooltip field, either a field selector
or an expression "f(k,v)" where f is a function
name that can be looked up from s3db, and k,v are
field selectors for the row, f will be called with
a list of tuples (k,v) for each row and is expected
to return a dict {k:tooltip} => used by
filterOptionsS3 to extract onhover-tooltips for
Ajax-update of options
"""
if fields is None:
# Use json_fields setting, or fall back to list_fields if
# not defined, or to all readable fields if list_fields is
# not defined either.
# Always include the ID field regardless whether it is
# configured or not => required for S3FilterOptions and
# similar Ajax lookups.
fields = resource.list_fields("json_fields", id_column=0)
if orderby is None:
orderby = resource.get_config("orderby", None)
tooltip_function = None
if tooltip:
if type(tooltip) is list:
tooltip = tooltip[-1]
import re
match = re.match("(\w+)\((\w+),(\w+)\)", tooltip)
if match:
function_name, kname, vname = match.groups()
# Try to resolve the function name
tooltip_function = current.s3db.get(function_name)
if tooltip_function:
if kname not in fields:
fields.append(kname)
if vname not in fields:
fields.append(vname)
else:
if tooltip not in fields:
fields.append(tooltip)
# Get the data
_rows = resource.select(fields,
start=start,
limit=limit,
orderby=orderby,
represent=represent).rows
# Simplify to plain fieldnames for fields in this table
tn = "%s." % resource.tablename
rows = []
rappend = rows.append
for _row in _rows:
row = {}
for f in _row:
v = _row[f]
if tn in f:
f = f.split(tn, 1)[1]
row[f] = v
rappend(row)
if tooltip:
if tooltip_function:
# Resolve key and value names against the resource
try:
krfield = resource.resolve_selector(kname)
vrfield = resource.resolve_selector(vname)
except (AttributeError, SyntaxError):
import sys
current.log.error(sys.exc_info()[1])
else:
# Extract key and value fields from each row and
# build options dict for function call
options = []
items = {}
for row in rows:
try:
k = krfield.extract(row)
except KeyError:
break
try:
v = vrfield.extract(row)
except KeyError:
break
items[k] = row
options.append((k, v))
# Call tooltip rendering function
try:
tooltips = tooltip_function(options)
except:
import sys
current.log.error(sys.exc_info()[1])
else:
# Add tooltips as "_tooltip" to the corresponding rows
if isinstance(tooltips, dict):
from s3utils import s3_unicode
for k, v in tooltips.items():
if k in items:
items[k]["_tooltip"] = s3_unicode(v)
else:
# Resolve the tooltip field name against the resource
try:
tooltip_rfield = resource.resolve_selector(tooltip)
except (AttributeError, SyntaxError):
import sys
current.log.error(sys.exc_info()[1])
else:
# Extract the tooltip field from each row
# and add it as _tooltip
from s3utils import s3_unicode
for row in rows:
try:
value = tooltip_rfield.extract(row)
except KeyError:
break
if value:
row["_tooltip"] = s3_unicode(value)
# Return as JSON
response = current.response
if response:
response.headers["Content-Type"] = "application/json"
from gluon.serializers import json as jsons
return jsons(rows)
0
File: swagger_model.py, Project: bravado, View licenseuses: bravado.compat.json.loads
def json(self):
return json.loads(self.text.decode('utf-8'))
0
File: tags.py, Project: grow, View licenseuses: grow.common.utils.memoize_tag
@utils.memoize_tag
def json(path, _pod):
return _pod.read_json(path)
0
File: models.py, Project: mootiro-maps, View licenseuses: main.utils.to_json
@property
def json(self):
return to_json(self.to_dict())
0
File: client.py, Project: flask-boilerplate, View licenseuses: flask.json.loads
@cached_property
def json(self):
assert self.mimetype == 'application/json'
return json.loads(self.data)
0
File: mispevent.py, Project: PyMISP, View licenseuses: jsonschema.validate
def _json(self):
to_return = {'Event': {}}
to_return['Event'] = {'distribution': self.distribution, 'info': self.info,
'date': self.date.isoformat(), 'published': self.published,
'threat_level_id': self.threat_level_id,
'analysis': self.analysis, 'Attribute': []}
if self.id:
to_return['Event']['id'] = self.id
if self.orgc_id:
to_return['Event']['orgc_id'] = self.orgc_id
if self.org_id:
to_return['Event']['org_id'] = self.org_id
if self.uuid:
to_return['Event']['uuid'] = self.uuid
if self.sharing_group_id:
to_return['Event']['sharing_group_id'] = self.sharing_group_id
if self.Tag:
to_return['Event']['Tag'] = self.Tag
to_return['Event'] = _int_to_str(to_return['Event'])
if self.attributes:
to_return['Event']['Attribute'] = [a._json() for a in self.attributes]
jsonschema.validate(to_return, self.json_schema)
return to_return
0
File: check_results.py, Project: tahoe-lafs, View licenseuses: nevow.inevow.IRequest.setHeader
def json(self, ctx):
inevow.IRequest(ctx).setHeader("content-type", "text/plain")
data = json_check_and_repair_results(self.r)
return simplejson.dumps(data, indent=1) + "\n"
0
File: SourcePosition.py, Project: coala, View licenseuses: coala_utils.decorators.get_public_members
def __json__(self, use_relpath=False):
_dict = get_public_members(self)
if use_relpath:
_dict['file'] = relpath(_dict['file'])
return _dict
0
File: status.py, Project: tahoe-lafs, View licenseuses: allmydata.util.base32.b2a_or_none
def json(self, req):
req.setHeader("content-type", "text/plain")
data = {}
data["active"] = active = []
for s in self._get_active_operations():
si_s = base32.b2a_or_none(s.get_storage_index())
size = s.get_size()
status = s.get_status()
if IUploadStatus.providedBy(s):
h,c,e = s.get_progress()
active.append({"type": "upload",
"storage-index-string": si_s,
"total-size": size,
"status": status,
"progress-hash": h,
"progress-ciphertext": c,
"progress-encode-push": e,
})
elif IDownloadStatus.providedBy(s):
active.append({"type": "download",
"storage-index-string": si_s,
"total-size": size,
"status": status,
"progress": s.get_progress(),
})
return simplejson.dumps(data, indent=1) + "\n"
0
File: base_entity.py, Project: v20-python, View licenseuses: ujson.dumps
def json(self):
return json.dumps(self.dict())
0
File: presets.py, Project: arista, View licenseuses: gst.Fraction
@property
def json(self):
data = {
"make": self.make,
"model": self.model,
"description": self.description,
"author": {
"name": self.author.name,
"email": self.author.email,
},
"version": self.version,
"icon": self.icon,
"default": self.default,
"presets": [],
}
for name, preset in self.presets.items():
rates = []
for x in preset.acodec.rate[0], preset.acodec.rate[1], preset.vcodec.rate[0], preset.vcodec.rate[1]:
if isinstance(x, gst.Fraction):
if x.denom == 1:
rates.append("%s" % x.num)
else:
rates.append("%s/%s" % (x.num, x.denom))
else:
rates.append("%s" % x)
data["presets"].append({
"name": preset.name,
"description": preset.description,
"author": {
"name": preset.author.name,
"email": preset.author.email,
},
"container": preset.container,
"extension": preset.extension,
"icon": preset.icon,
"version": preset.version,
"acodec": {
"name": preset.acodec.name,
"container": preset.acodec.container,
"rate": [rates[0], rates[1]],
"passes": preset.acodec.passes,
"width": preset.acodec.width,
"depth": preset.acodec.depth,
"channels": preset.acodec.channels,
},
"vcodec": {
"name": preset.vcodec.name,
"container": preset.vcodec.container,
"rate": [rates[2], rates[3]],
"passes": preset.vcodec.passes,
"width": preset.vcodec.width,
"height": preset.vcodec.height,
"transform": preset.vcodec.transform,
},
})
return json.dumps(data, indent=4)
0
File: graph.py, Project: reprozip, View licenseuses: rpaths.PosixPath
def json(self, process_map):
name = "%d" % self.pid
long_name = "%s (%d)" % (PosixPath(self.binary).components[-1]
if self.binary else "-",
self.pid)
description = "%s\n%d" % (self.binary, self.pid)
if self.parent is not None:
if self.created == C_FORK:
reason = "fork"
elif self.created == C_EXEC:
reason = "exec"
elif self.created == C_FORKEXEC:
reason = "fork+exec"
else:
assert False
parent = [process_map[self.parent], reason]
else:
parent = None
return {'name': name, 'parent': parent, 'reads': [], 'writes': [],
'long_name': long_name, 'description': description}
0
File: refresh.py, Project: exabgp, View licenseuses: exabgp.bgp.message.open.capability.capability.Capability.CODE.ROUTE_REFRESH
def json (self):
return '{ "name": "route-refresh", "variant": "%s" }' % ('RFC' if self.ID == Capability.CODE.ROUTE_REFRESH else 'Cisco')
0
File: manage.py, Project: pulsar, View licenseuses: pulsar.apps.wsgi.Json.http_response
@route()
def json(self, request):
return Json({'message': "Hello, World!"}).http_response(request)
0
File: beattv.py, Project: streamlink, View licenseuses: streamlink.stream.Stream.__json__
def __json__(self):
return dict(parts=self.parts, quality=self.quality,
**Stream.__json__(self))
0
File: json.py, Project: python-fedora, View licenseuses: sqlalchemy.orm.object_mapper.iterate_properties
def __json__(self):
'''Transform any SA mapped class into json.
This method takes an SA mapped class and turns the "normal" python
attributes into json. The properties (from properties in the mapper)
are also included if they have an entry in json_props. You make
use of this by setting json_props in the controller.
Example controller::
john = model.Person.get_by(name='John')
# Person has a property, addresses, linking it to an Address class.
# Address has a property, phone_nums, linking it to a Phone class.
john.json_props = {'Person': ['addresses'],
'Address': ['phone_nums']}
return dict(person=john)
json_props is a dict that maps class names to lists of properties you
want to output. This allows you to selectively pick properties you
are interested in for one class but not another. You are responsible
for avoiding loops. ie: *don't* do this::
john.json_props = {'Person': ['addresses'], 'Address': ['people']}
'''
props = {}
prop_list = {}
if hasattr(self, 'json_props'):
for base_class in self.__class__.__mro__:
# pylint: disable-msg=E1101
if base_class.__name__ in self.json_props:
prop_list = self.json_props[base_class.__name__]
break
# pylint: enable-msg=E1101
# Load all the columns from the table
for column in sqlalchemy.orm.object_mapper(self).iterate_properties:
if isinstance(column, sqlalchemy.orm.properties.ColumnProperty):
props[column.key] = getattr(self, column.key)
# Load things that are explicitly listed
for field in prop_list:
props[field] = getattr(self, field)
try:
# pylint: disable-msg=E1101
props[field].json_props = self.json_props
except AttributeError: # pylint: disable-msg=W0704
# :W0704: Certain types of objects are terminal and won't
# allow setting json_props
pass
# Note: Because of the architecture of simplejson and turbojson,
# anything that inherits from a builtin list, tuple, basestring,
# or dict but needs special handling needs to be specified
# expicitly here. Using the @jsonify.when() decorator won't work.
if isinstance(props[field],
sqlalchemy.orm.collections.InstrumentedList):
props[field] = jsonify_salist(props[field])
return props