query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
map to json
|
python
|
def parse_map(self, obj, mapping=None, *args, **kwargs):
""" Parses a dictionary of (model_attr, json_attr) items """
mapping = mapping or obj._mapping
if "data" in kwargs:
for k, v in mapping.items():
if kwargs["data"].get(v, None) is not None:
val = kwargs["data"][v]
else:
val = None
self.add_attr(obj, k, val, from_json=True)
else:
for k, v in mapping.items():
if k in kwargs:
self.add_attr(obj, k, kwargs[k])
|
https://github.com/xray7224/PyPump/blob/f921f691c39fe021f4fd124b6bc91718c9e49b4a/pypump/models/__init__.py#L212-L226
|
map to json
|
python
|
def maps_json():
"""
Generates a json object which serves as bridge between
the web interface and the map source collection.
All attributes relevant for openlayers are converted into
JSON and served through this route.
Returns:
Response: All map sources as JSON object.
"""
map_sources = {
id: {
"id": map_source.id,
"name": map_source.name,
"folder": map_source.folder,
"min_zoom": map_source.min_zoom,
"max_zoom": map_source.max_zoom,
"layers": [
{
"min_zoom": layer.min_zoom,
"max_zoom": layer.max_zoom,
"tile_url": layer.tile_url.replace("$", ""),
} for layer in map_source.layers
]
} for id, map_source in app.config["mapsources"].items()
}
return jsonify(map_sources)
|
https://github.com/grst/geos/blob/ea15abcc5d8f86c9051df55e489b7d941b51a638/geos/server.py#L25-L53
|
map to json
|
python
|
def jsonrpc_map(self, request):
""" Map of json-rpc available calls.
:return str:
"""
result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([
"{0}: {1}".format(fname, f.__doc__)
for fname, f in self.dispatcher.items()
]))
return HttpResponse(result)
|
https://github.com/AirtestProject/Poco/blob/2c559a586adf3fd11ee81cabc446d4d3f6f2d119/poco/utils/simplerpc/jsonrpc/backend/django.py#L69-L79
|
map to json
|
python
|
def getmap(self, path, query=None):
"""
Performs a GET request where the response content type is required to be
"application/json" and the content is a JSON-encoded data structure.
The decoded structure is returned.
"""
code, data, ctype = self.get(path, query)
if ctype != 'application/json':
self.log.error("Expecting JSON from GET of '%s', got '%s'", self.lastpath, ctype)
raise HttpError(code=400, content_type='text/plain', content='Remote returned invalid content type: '+ctype)
try:
result = json.loads(data)
except Exception as e: # pragma: no cover
self.log.error("Could not load JSON content from GET %r -- %s", self.lastpath, e)
raise HttpError(code=400, content_type='text/plain', content='Could not load JSON content')
return result
|
https://github.com/akfullfo/taskforce/blob/bc6dd744bd33546447d085dbd18a350532220193/taskforce/http.py#L220-L235
|
map to json
|
python
|
def jsonrpc_map(self):
""" Map of json-rpc available calls.
:return str:
"""
result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([
"{0}: {1}".format(fname, f.__doc__)
for fname, f in self.dispatcher.items()
]))
return Response(result)
|
https://github.com/AirtestProject/Poco/blob/2c559a586adf3fd11ee81cabc446d4d3f6f2d119/poco/utils/simplerpc/jsonrpc/backend/flask.py#L69-L79
|
map to json
|
python
|
def to_json(self):
"""Serializes all the data in this query range into json form.
Returns:
all the data in json-compatible map.
"""
return {self.NAMESPACE_RANGE_PARAM: self.ns_range.to_json_object(),
self.BATCH_SIZE_PARAM: self._batch_size}
|
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/input_readers.py#L1944-L1951
|
map to json
|
python
|
def to_json(self):
"""Serializes all data in this mapreduce spec into json form.
Returns:
data in json format.
"""
mapper_spec = self.mapper.to_json()
return {
"name": self.name,
"mapreduce_id": self.mapreduce_id,
"mapper_spec": mapper_spec,
"params": self.params,
"hooks_class_name": self.hooks_class_name,
}
|
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/model.py#L502-L515
|
map to json
|
python
|
def to_nullable_map(value):
"""
Converts JSON string into map object or returns null when conversion is not possible.
:param value: the JSON string to convert.
:return: Map object value or null when conversion is not supported.
"""
if value == None:
return None
# Parse JSON
try:
value = json.loads(value)
return RecursiveMapConverter.to_nullable_map(value)
except:
return None
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/convert/JsonConverter.py#L53-L69
|
map to json
|
python
|
def _map_value(self, value):
''' Maps a raw deserialized row to proper types '''
# TODO: Once we've gotten here, we've done the following:
# -> Recieve the full response, copy it from network buffer it into a ByteBuffer (copy 1)
# -> Copy all the data into a String (copy 2)
# -> Deserialize that string (copy 3)
# -> Map the deserialized JSON to our response format (copy 4, what we are doing in this method)
# This should not bee needed. Technically, this mapping from transport format to python types should require exactly one copy,
# from the network buffer into the python VM.
if isinstance(value, list):
out = []
for c in value:
out.append(self._map_value( c ))
return out
elif isinstance(value, dict) and 'metadata' in value and 'labels' in value['metadata'] and 'self' in value:
return neo4j.Node(ustr(value['metadata']['id']), value['metadata']['labels'], value['data'])
elif isinstance(value, dict) and 'metadata' in value and 'type' in value and 'self' in value:
return neo4j.Relationship(ustr(value['metadata']['id']), value['type'], value['start'].split('/')[-1], value['end'].split('/')[-1], value['data'])
elif isinstance(value, dict):
out = {}
for k,v in value.items():
out[k] = self._map_value( v )
return out
elif isinstance(value, str):
return ustr(value)
else:
return value
|
https://github.com/jakewins/neo4jdb-python/blob/cd78cb8397885f219500fb1080d301f0c900f7be/neo4j/cursor.py#L123-L149
|
map to json
|
python
|
def to_json(self):
"""Serializes all the data in this query range into json form.
Returns:
all the data in json-compatible map.
"""
if self._key_ranges is None:
key_ranges_json = None
else:
key_ranges_json = []
for k in self._key_ranges:
if k:
key_ranges_json.append(k.to_json())
else:
key_ranges_json.append(None)
if self._ns_range is None:
namespace_range_json = None
else:
namespace_range_json = self._ns_range.to_json_object()
if self._current_key_range is None:
current_key_range_json = None
else:
current_key_range_json = self._current_key_range.to_json()
json_dict = {self.KEY_RANGE_PARAM: key_ranges_json,
self.NAMESPACE_RANGE_PARAM: namespace_range_json,
self.CURRENT_KEY_RANGE_PARAM: current_key_range_json,
self.ENTITY_KIND_PARAM: self._entity_kind,
self.BATCH_SIZE_PARAM: self._batch_size,
self.FILTERS_PARAM: self._filters}
return json_dict
|
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/input_readers.py#L1210-L1242
|
map to json
|
python
|
def to_json(self):
"""Create a location from json.
{
"city": "-",
"latitude": 0,
"longitude": 0,
"time_zone": 0,
"elevation": 0
}
"""
return {
"city": self.city,
"state": self.state,
"country": self.country,
"latitude": self.latitude,
"longitude": self.longitude,
"time_zone": self.time_zone,
"elevation": self.elevation,
"station_id": self.station_id,
"source": self.source
}
|
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/location.py#L182-L202
|
map to json
|
python
|
def emit_map(self, m, _, cache):
"""Emits array as per default JSON spec."""
self.emit_array_start(None)
self.marshal(MAP_AS_ARR, False, cache)
for k, v in m.items():
self.marshal(k, True, cache)
self.marshal(v, False, cache)
self.emit_array_end()
|
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L353-L360
|
map to json
|
python
|
def to_map_with_default(value, default_value):
"""
Converts JSON string into map object or returns default value when conversion is not possible.
:param value: the JSON string to convert.
:param default_value: the default value.
:return: Map object value or default when conversion is not supported.
"""
result = JsonConverter.to_nullable_map(value)
return result if result != None else default_value
|
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/convert/JsonConverter.py#L84-L95
|
map to json
|
python
|
def to_json(self):
"""Serializes all states into json form.
Returns:
all states in json-compatible map.
"""
cursor = self._get_cursor()
cursor_object = False
if cursor and isinstance(cursor, datastore_query.Cursor):
cursor = cursor.to_websafe_string()
cursor_object = True
return {"key_range": self._key_range.to_json(),
"query_spec": self._query_spec.to_json(),
"cursor": cursor,
"cursor_object": cursor_object}
|
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/datastore_range_iterators.py#L405-L419
|
map to json
|
python
|
def postmap(self, path, valuemap=None, query=None):
"""
Performs a POST request as per post() but the response content type
is required to be "application/json" and is processed as with getmap().
"""
code, data, ctype = self.post(path, valuemap, query)
if ctype != 'application/json':
self.log.error("Expecting JSON from POST of '%s', got '%s'", self.lastpath, ctype)
raise HttpError(code=400, content_type='text/plain', content='Remote returned invalid content type: '+ctype)
try:
result = json.loads(data)
except Exception as e: # pragma: no cover
self.log.error("Could not load JSON content from POST %r -- %s", self.lastpath, e)
raise HttpError(code=400, content_type='text/plain', content='Could not load JSON content')
return result
|
https://github.com/akfullfo/taskforce/blob/bc6dd744bd33546447d085dbd18a350532220193/taskforce/http.py#L259-L273
|
map to json
|
python
|
def to_json(self, obj, host=None, indent=None):
"""Recursively encode `obj` and convert it to a JSON string.
:param obj:
Object to encode.
:param host:
hostname where this object is being encoded.
:type host: str"""
if indent:
return json.dumps(deep_map(lambda o: self.encode(o, host), obj),
indent=indent)
else:
return json.dumps(deep_map(lambda o: self.encode(o, host), obj))
|
https://github.com/NLeSC/noodles/blob/3759e24e6e54a3a1a364431309dbb1061f617c04/noodles/serial/registry.py#L236-L249
|
map to json
|
python
|
def json(
self,
filepath=None
):
"""*Render the data in json format*
**Key Arguments:**
- ``filepath`` -- path to the file to write the json content to. Default *None*
**Return:**
- ``renderedData`` -- the data rendered as json
**Usage:**
To render the data set as json:
.. code-block:: python
print dataSet.json()
.. code-block:: json
[
{
"address": "belfast, uk",
"owner": "daisy",
"pet": "dog"
},
{
"address": "the moon",
"owner": "john",
"pet": "snake"
},
{
"address": "larne",
"owner": "susan",
"pet": "crocodile"
}
]
and to save the json rendering to file:
.. code-block:: python
dataSet.json("/path/to/myfile.json")
"""
self.log.debug('starting the ``json`` method')
dataCopy = copy.deepcopy(self.listOfDictionaries)
for d in dataCopy:
for k, v in d.iteritems():
if isinstance(v, datetime):
d[k] = v.strftime("%Y%m%dt%H%M%S")
renderedData = json.dumps(
dataCopy,
separators=(',', ': '),
sort_keys=True,
indent=4
)
if filepath and len(self.listOfDictionaries):
# RECURSIVELY CREATE MISSING DIRECTORIES
if not os.path.exists(os.path.dirname(filepath)):
os.makedirs(os.path.dirname(filepath))
writeFile = codecs.open(filepath, encoding='utf-8', mode='w')
writeFile.write(renderedData)
writeFile.close()
self.log.debug('completed the ``json`` method')
return renderedData
|
https://github.com/thespacedoctor/fundamentals/blob/1d2c007ac74442ec2eabde771cfcacdb9c1ab382/fundamentals/renderer/list_of_dictionaries.py#L306-L378
|
map to json
|
python
|
def map_to_dictionary(self, url, obj, **kwargs):
"""
Build a dictionary of metadata for the requested object.
"""
maxwidth = kwargs.get('maxwidth', None)
maxheight = kwargs.get('maxheight', None)
provider_url, provider_name = self.provider_from_url(url)
mapping = {
'version': '1.0',
'url': url,
'provider_name': provider_name,
'provider_url': provider_url,
'type': self.resource_type
}
# a hook
self.preprocess(obj, mapping, **kwargs)
# resize image if we have a photo, otherwise use the given maximums
if self.resource_type == 'photo' and self.get_image(obj):
self.resize_photo(obj, mapping, maxwidth, maxheight)
elif self.resource_type in ('video', 'rich', 'photo'):
width, height = size_to_nearest(
maxwidth,
maxheight,
self._meta.valid_sizes,
self._meta.force_fit
)
mapping.update(width=width, height=height)
# create a thumbnail
if self.get_image(obj):
self.thumbnail(obj, mapping)
# map attributes to the mapping dictionary. if the attribute is
# a callable, it must have an argument signature of
# (self, obj)
for attr in ('title', 'author_name', 'author_url', 'html'):
self.map_attr(mapping, attr, obj)
# fix any urls
if 'url' in mapping:
mapping['url'] = relative_to_full(mapping['url'], url)
if 'thumbnail_url' in mapping:
mapping['thumbnail_url'] = relative_to_full(mapping['thumbnail_url'], url)
if 'html' not in mapping and mapping['type'] in ('video', 'rich'):
mapping['html'] = self.render_html(obj, context=Context(mapping))
# a hook
self.postprocess(obj, mapping, **kwargs)
return mapping
|
https://github.com/worldcompany/djangoembed/blob/f3f2be283441d91d1f89db780444dc75f7b51902/oembed/providers.py#L513-L568
|
map to json
|
python
|
def to_json(self, buffer_or_path=None, indent=2):
"""
Parameters
----------
buffer_or_path: buffer or path, default None
output to write into. If None, will return a json string.
indent: int, default 2
Defines the indentation of the json
Returns
-------
None, or a json string (if buffer_or_path is None).
"""
# return json
return json_data_to_json(
self.to_json_data(),
buffer_or_path=buffer_or_path,
indent=indent
)
|
https://github.com/openergy/oplus/blob/f095868d1990c1d126e906ada6acbab26348b3d3/oplus/epm/epm.py#L299-L317
|
map to json
|
python
|
def decode_map(self, data_type, obj):
"""
The data_type argument must be a Map.
See json_compat_obj_decode() for argument descriptions.
"""
if not isinstance(obj, dict):
raise bv.ValidationError(
'expected dict, got %s' % bv.generic_type_name(obj))
return {
self.json_compat_obj_decode_helper(data_type.key_validator, key):
self.json_compat_obj_decode_helper(data_type.value_validator, value)
for key, value in obj.items()
}
|
https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/backends/python_rsrc/stone_serializers.py#L849-L861
|
map to json
|
python
|
def json_data(self, instance, default=[]):
"""Get a JSON compatible value
"""
value = self.get(instance)
out = map(api.get_url_info, value)
return out or default
|
https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/fieldmanagers.py#L542-L547
|
map to json
|
python
|
def to_json(self, default_mapping=None):
"""
Dump json of the text view.
**Parameters**
default_mapping : default_mapping, dictionary(optional), a dictionary of mapping of different types to json types.
by default DeepDiff converts certain data types. For example Decimals into floats so they can be exported into json.
If you have a certain object type that the json serializer can not serialize it, please pass the appropriate type
conversion through this dictionary.
**Example**
Serialize custom objects
>>> class A:
... pass
...
>>> class B:
... pass
...
>>> t1 = A()
>>> t2 = B()
>>> ddiff = DeepDiff(t1, t2)
>>> ddiff.to_json()
TypeError: We do not know how to convert <__main__.A object at 0x10648> of type <class '__main__.A'> for json serialization. Please pass the default_mapping parameter with proper mapping of the object to a basic python type.
>>> default_mapping = {A: lambda x: 'obj A', B: lambda x: 'obj B'}
>>> ddiff.to_json(default_mapping=default_mapping)
'{"type_changes": {"root": {"old_type": "A", "new_type": "B", "old_value": "obj A", "new_value": "obj B"}}}'
"""
return json.dumps(self.to_dict(), default=json_convertor_default(default_mapping=default_mapping))
|
https://github.com/seperman/deepdiff/blob/a66879190fadc671632f154c1fcb82f5c3cef800/deepdiff/diff.py#L680-L710
|
map to json
|
python
|
def parse_json(json_string, object_type, mappers):
"""
This function will use the custom JsonDecoder and the conventions.mappers to recreate your custom object
in the parse json string state just call this method with the json_string your complete object_type and with your
mappers dict.
the mappers dict must contain in the key the object_type (ex. User) and the value will contain a method that get
key, value (the key will be the name of the object property we like to parse and the value
will be the properties of the object)
"""
obj = json.loads(json_string, cls=JsonDecoder, object_mapper=mappers.get(object_type, None))
if obj is not None:
try:
obj = object_type(**obj)
except TypeError:
initialize_dict, set_needed = Utils.make_initialize_dict(obj, object_type.__init__)
o = object_type(**initialize_dict)
if set_needed:
for key, value in obj.items():
setattr(o, key, value)
obj = o
return obj
|
https://github.com/ravendb/ravendb-python-client/blob/383739db2594303e3cc469134aa16156f6f80acd/pyravendb/tools/custom_decoder.py#L28-L49
|
map to json
|
python
|
def to_json(self, path: Optional[str] = None, **kwargs) -> str:
"""Convert to JSON representation.
Parameters
----------
path: Where to write the JSON.
Returns
-------
The JSON representation.
"""
from .io import save_json
return save_json(self, path, **kwargs)
|
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_collection.py#L171-L183
|
map to json
|
python
|
def to_json(self, *args, **kwargs):
"""Return a json representation (str) of this blob. Takes the same
arguments as json.dumps.
.. versionadded:: 0.5.1 (``textblob``)
"""
return json.dumps(self.serialized, *args, **kwargs)
|
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/blob.py#L728-L735
|
map to json
|
python
|
def to_json(self) -> Mapping:
"""Return the properties of this :class:`Sample` as JSON serializable.
"""
return {str(x): str(y) for x, y in self.items()}
|
https://github.com/clintval/sample-sheet/blob/116ac6f26f6e61b57716c90f6e887d3d457756f3/sample_sheet/__init__.py#L312-L316
|
map to json
|
python
|
def to_json(self, path, root_array=True, mode=WRITE_MODE, compression=None):
"""
Saves the sequence to a json file. If root_array is True, then the sequence will be written
to json with an array at the root. If it is False, then the sequence will be converted from
a sequence of (Key, Value) pairs to a dictionary so that the json root is a dictionary.
:param path: path to write file
:param root_array: write json root as an array or dictionary
:param mode: file open mode
"""
with universal_write_open(path, mode=mode, compression=compression) as output:
if root_array:
json.dump(self.to_list(), output)
else:
json.dump(self.to_dict(), output)
|
https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1509-L1523
|
map to json
|
python
|
def from_json(buffer):
"""Creates a sourcemap view from a JSON string."""
buffer = to_bytes(buffer)
return View._from_ptr(rustcall(
_lib.lsm_view_from_json,
buffer, len(buffer)))
|
https://github.com/getsentry/libsourcemap/blob/94b5a34814fafee9dc23da8ec0ccca77f30e3370/libsourcemap/highlevel.py#L106-L111
|
map to json
|
python
|
def __convert_json_to_projects_map(self, json):
""" Convert JSON format to the projects map format
map[ds][repository] = project
If a repository is in several projects assign to leaf
Check that all JSON data is in the database
:param json: data with the projects to repositories mapping
:returns: the repositories to projects mapping per data source
"""
ds_repo_to_prj = {}
for project in json:
for ds in json[project]:
if ds == "meta":
continue # not a real data source
if ds not in ds_repo_to_prj:
if ds not in ds_repo_to_prj:
ds_repo_to_prj[ds] = {}
for repo in json[project][ds]:
if repo in ds_repo_to_prj[ds]:
if project == ds_repo_to_prj[ds][repo]:
logger.debug("Duplicated repo: %s %s %s", ds, repo, project)
else:
if len(project.split(".")) > len(ds_repo_to_prj[ds][repo].split(".")):
logger.debug("Changed repo project because we found a leaf: %s leaf vs %s (%s, %s)",
project, ds_repo_to_prj[ds][repo], repo, ds)
ds_repo_to_prj[ds][repo] = project
else:
ds_repo_to_prj[ds][repo] = project
return ds_repo_to_prj
|
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/enrich.py#L198-L227
|
map to json
|
python
|
def to_JSON(self):
"""Dumps object fields into a JSON formatted string
:returns: the JSON string
"""
return json.dumps({"interval": self._interval,
"reception_time": self._reception_time,
"Location": json.loads(self._location.to_JSON()),
"weathers": json.loads("[" + \
",".join([w.to_JSON() for w in self]) + "]")
})
|
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/forecast.py#L171-L182
|
map to json
|
python
|
def json(
klass,
map=None,
allow_404=True,
one=False,
decode=False,
is_id=False,
index=False):
"""
*map* is a function to apply to the final result.
*allow_404* if set, None will be returned on 404, instead of raising
NotFound.
*index* if set, a tuple of index, data will be returned.
*one* returns only the first item of the list of items. empty lists are
coerced to None.
*decode* if specified this key will be base64 decoded.
*is_id* only the 'ID' field of the json object will be returned.
"""
def cb(response):
CB._status(response, allow_404=allow_404)
if response.code == 404:
return response.headers['X-Consul-Index'], None
data = json.loads(response.body)
if decode:
for item in data:
if item.get(decode) is not None:
item[decode] = base64.b64decode(item[decode])
if is_id:
data = data['ID']
if one:
if data == []:
data = None
if data is not None:
data = data[0]
if map:
data = map(data)
if index:
return response.headers['X-Consul-Index'], data
return data
return cb
|
https://github.com/cablehead/python-consul/blob/53eb41c4760b983aec878ef73e72c11e0af501bb/consul/base.py#L199-L245
|
map to json
|
python
|
def to_json(self):
"""
Returns:
str: Json for commands array object and all of the commands inside the array."""
commands = ",".join(map(lambda x: x.to_json(), self._commands))
return "{\"commands\": [" + commands + "]}"
|
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/command.py#L22-L27
|
map to json
|
python
|
def get_json(self, path, watch=None):
"""Reads the data of the specified node and converts it to json."""
data, _ = self.get(path, watch)
return load_json(data) if data else None
|
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/zookeeper.py#L82-L85
|
map to json
|
python
|
def to_json(self):
"""Serialize an object to JSON based on its "properties" class
attribute.
:rtype: string"""
j = {}
for p in self.properties:
j[p] = getattr(self, p)
return json.dumps(j)
|
https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/protocol/objects.py#L59-L69
|
map to json
|
python
|
def to_json(self, **kwargs: Mapping) -> str:
"""Write this :class:`SampleSheet` to JSON.
Returns:
str: The JSON dump of all entries in this sample sheet.
"""
content = {
'Header': dict(self.Header),
'Reads': self.Reads,
'Settings': dict(self.Settings),
'Data': [sample.to_json() for sample in self.samples],
**{title: dict(getattr(self, title)) for title in self._sections},
}
return json.dumps(content, **kwargs)
|
https://github.com/clintval/sample-sheet/blob/116ac6f26f6e61b57716c90f6e887d3d457756f3/sample_sheet/__init__.py#L683-L697
|
map to json
|
python
|
def api_path_map(self):
"""Cached dict of api_path: func."""
if self._api_path_cache is None:
self._api_path_cache = {
api_path: func
for api_path, func
in api_endpoints(self)
}
return self._api_path_cache
|
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/api.py#L149-L157
|
map to json
|
python
|
def geojson_handler(geojson, hType='map'):
"""Restructure a GeoJSON object in preparation to be added directly by add_map_data or add_data_set methods.
The geojson will be broken down to fit a specific Highcharts (highmaps) type, either map, mapline or mappoint.
Meta data in GeoJSON's properties object will be copied directly over to object['properties']
1. geojson is the map data (GeoJSON) to be converted
2. hType is the type of highmap types. "map" will return GeoJSON polygons and multipolygons.
"mapline" will return GeoJSON linestrings and multilinestrings.
"mappoint" will return GeoJSON points and multipoints.
default: "map"
"""
hType_dict = {
'map': ['polygon', 'multipolygon'],
'mapline': ['linestring', 'multilinestring'],
'mappoint': ['point', 'multipoint'],
}
oldlist = [x for x in geojson['features'] if x['geometry']['type'].lower() in hType_dict[hType]]
newlist = []
for each_dict in oldlist:
geojson_type = each_dict['geometry']['type'].lower()
if hType == 'mapline':
newlist.append(
{'name': each_dict['properties'].get('name', None),
'path': _coordinates_to_path(each_dict['geometry']['coordinates'], hType, geojson_type),
'properties': each_dict['properties'],
}
)
elif hType == 'map':
newlist.append(
{'name': each_dict['properties']['name'],
'path': _coordinates_to_path(each_dict['geometry']['coordinates'], hType, geojson_type),
'properties': each_dict['properties'],
}
)
elif hType == 'mappoint':
newlist.append(
{'name': each_dict['properties']['name'],
'x': each_dict['geometry']['coordinates'][0],
'y': -each_dict['geometry']['coordinates'][1],
'properties': each_dict['properties'],
}
)
return newlist
|
https://github.com/kyper-data/python-highcharts/blob/a4c488ae5c2e125616efad5a722f3dfd8a9bc450/highcharts/highmaps/highmap_helper.py#L51-L97
|
map to json
|
python
|
def to_json(self):
""" Converts segment to a JSON serializable format
Returns:
:obj:`dict`
"""
points = [point.to_json() for point in self.points]
return {
'points': points,
'transportationModes': self.transportation_modes,
'locationFrom': self.location_from.to_json() if self.location_from != None else None,
'locationTo': self.location_to.to_json() if self.location_to != None else None
}
|
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L290-L302
|
map to json
|
python
|
def to_JSON(self):
"""Dumps object fields into a JSON formatted string
:returns: the JSON string
"""
return json.dumps({"reception_time": self._reception_time,
"Location": json.loads(self._location.to_JSON()),
"Weather": json.loads(self._weather.to_JSON())
})
|
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/observation.py#L72-L81
|
map to json
|
python
|
def to_json(self, depth=-1, **kwargs):
"""Returns a JSON representation of the object."""
return json.dumps(self.to_dict(depth=depth, ordered=True), **kwargs)
|
https://github.com/python-visualization/branca/blob/4e89e88a5a7ff3586f0852249c2c125f72316da8/branca/element.py#L138-L140
|
map to json
|
python
|
def to_json(self):
"""Serializes this MapperSpec into a json-izable object."""
result = {
"mapper_handler_spec": self.handler_spec,
"mapper_input_reader": self.input_reader_spec,
"mapper_params": self.params,
"mapper_shard_count": self.shard_count
}
if self.output_writer_spec:
result["mapper_output_writer"] = self.output_writer_spec
return result
|
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/model.py#L412-L422
|
map to json
|
python
|
def class_to_json(obj):
"""
:type obj: int|str|bool|float|bytes|unicode|list|dict|object
:rtype: int|str|bool|list|dict
"""
obj_raw = serialize(obj)
return json.dumps(obj_raw, indent=_JSON_INDENT, sort_keys=True)
|
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/json/converter.py#L665-L674
|
map to json
|
python
|
def serialize(self):
"""
Serializes the node data as a JSON map string.
"""
return json.dumps({
"port": self.port,
"ip": self.ip,
"host": self.host,
"peer": self.peer.serialize() if self.peer else None,
"metadata": json.dumps(self.metadata or {}, sort_keys=True),
}, sort_keys=True)
|
https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/node.py#L50-L60
|
map to json
|
python
|
def _write_json(obj, path): # type: (object, str) -> None
"""Writes a serializeable object as a JSON file"""
with open(path, 'w') as f:
json.dump(obj, f)
|
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_env.py#L36-L39
|
map to json
|
python
|
def from_json(self):
'''
Reads dataset from json.
'''
with gzip.open('%s.gz' % self.path,
'rt') if self.gz else open(self.path) as file:
return list(map(list, zip(*json.load(file))))[::-1]
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/utils/skutils_io.py#L40-L46
|
map to json
|
python
|
def to_json(self):
"""Return a JSON-serializable representation."""
return {
'network': self.network,
'state': self.state,
'nodes': self.node_indices,
'cut': self.cut,
}
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L238-L245
|
map to json
|
python
|
def to_json(self):
"""Exports the object to a JSON friendly dict
Returns:
Dict representation of the object
"""
return {
'userId': self.user_id,
'username': self.username,
'roles': self.roles,
'authSystem': self.auth_system
}
|
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/schema/base.py#L370-L381
|
map to json
|
python
|
def to_json(self):
"""
Convert to a json-serializable representation.
Returns:
dict: A dict representation that is json-serializable.
"""
return {
"xblock_id": six.text_type(self.xblock_id),
"messages": [message.to_json() for message in self.messages],
"empty": self.empty
}
|
https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/validation.py#L111-L122
|
map to json
|
python
|
def to_json(self):
"""
Serialize to JSON, which can be returned e.g. via RPC
"""
ret = {
'address': self.address,
'domain': self.domain,
'block_number': self.block_height,
'sequence': self.n,
'txid': self.txid,
'value_hash': get_zonefile_data_hash(self.zonefile_str),
'zonefile': base64.b64encode(self.zonefile_str),
'name': self.get_fqn(),
}
if self.pending is not None:
ret['pending'] = self.pending
if self.resolver is not None:
ret['resolver'] = self.resolver
return ret
|
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L235-L256
|
map to json
|
python
|
def to_json(self):
"""Return a JSON-serializable representation."""
return {
'tpm': self.tpm,
'cm': self.cm,
'size': self.size,
'node_labels': self.node_labels
}
|
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/network.py#L198-L205
|
map to json
|
python
|
def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:
"""
Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object.
"""
return {k: v for k, v in obj.items() if v is not None}
|
https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/utils.py#L176-L181
|
map to json
|
python
|
def serialize_to_json(data, **kwargs):
"""
A wrapper for simplejson.dumps with defaults as:
cls=LazyJSONEncoder
All arguments can be added via kwargs
"""
kwargs['cls'] = kwargs.get('cls', LazyJSONEncoder)
return json.dumps(data, **kwargs)
|
https://github.com/yceruto/django-ajax/blob/d5af47c0e65571d4729f48781c0b41886b926221/django_ajax/encoder.py#L58-L68
|
map to json
|
python
|
def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['local_control'] = self.local_control
json_dict['status_mode'] = DSTATUS[self.status_mode]
json_dict['auto_send'] = self.auto_send
json_dict['mode'] = DMODE[self.mode]
json_dict['cool'] = self.cool
json_dict['heater'] = self.heater
json_dict['boost'] = self.boost
json_dict['pump'] = self.pump
json_dict['cool'] = self.cool
json_dict['alarm1'] = self.alarm1
json_dict['alarm2'] = self.alarm2
json_dict['alarm3'] = self.alarm3
json_dict['alarm4'] = self.alarm4
json_dict['current_temp'] = self.current_temp
json_dict['target_temp'] = self.target_temp
json_dict['sleep_timer'] = self.sleep_timer
return json.dumps(json_dict)
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/messages/temp_sensor_status.py#L90-L111
|
map to json
|
python
|
def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['channel'] = self.channel
json_dict['timeout'] = self.timeout
json_dict['status'] = self.status
json_dict['led_status'] = self.led_status
json_dict['blind_position'] = self.blind_position
json_dict['locked_inhibit_forced'] = self.locked_inhibit_forced
json_dict['alarm_auto_mode_selection'] = self.alarm_auto_mode_selection
return json.dumps(json_dict)
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/messages/blind_status.py#L83-L95
|
map to json
|
python
|
def to_json(self):
''' NetworkDescriptor to json representation
'''
skip_list = []
for u, v, connection_type in self.skip_connections:
skip_list.append({"from": u, "to": v, "type": connection_type})
return {"node_list": self.layers, "skip_list": skip_list}
|
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L89-L96
|
map to json
|
python
|
def get_json(self, prettyprint=False, translate=True):
"""
Get the data in JSON form
"""
j = []
if translate:
d = self.get_translated_data()
else:
d = self.data
for k in d:
j.append(d[k])
if prettyprint:
j = json.dumps(j, indent=2, separators=(',',': '))
else:
j = json.dumps(j)
return j
|
https://github.com/zwischenloesung/ardu-report-lib/blob/51bd4a07e036065aafcb1273b151bea3fdfa50fa/libardurep/datastore.py#L190-L205
|
map to json
|
python
|
def describe_token_map(self, ):
"""
get the mapping between token->node ip
without taking replication into consideration
https://issues.apache.org/jira/browse/CASSANDRA-4092
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_describe_token_map()
return d
|
https://github.com/driftx/Telephus/blob/860a03a0fafe71605e1a4316dfdd8d0c29094703/telephus/cassandra/Cassandra.py#L1400-L1409
|
map to json
|
python
|
def get_map_data(self):
"""
Returns a serializable data set describing the map location
"""
return {
'containerSelector': '#' + self.get_map_element_id(),
'center': self.map_center_description,
'marker': self.map_marker_description or self.map_center_description,
'zoom': self.map_zoom,
'href': self.get_map_href(),
'key': getattr(settings, 'GOOGLE_MAPS_API_KEY', ''),
# Python's line-splitting is more cross-OS compatible, so we feed
# a pre-built array to the front-end
'description': [
line for line in self.map_description.splitlines() if line
],
}
|
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/mixins.py#L434-L451
|
map to json
|
python
|
def append_json(
self,
obj: Any,
headers: Optional['MultiMapping[str]']=None
) -> Payload:
"""Helper to append JSON part."""
if headers is None:
headers = CIMultiDict()
return self.append_payload(JsonPayload(obj, headers=headers))
|
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/multipart.py#L832-L841
|
map to json
|
python
|
def to_JSON(self):
"""Dumps object fields into a JSON formatted string
:returns: the JSON string
"""
return json.dumps({"reference_time": self._reference_time,
"location": json.loads(self._location.to_JSON()),
"value": self._value,
"reception_time": self._reception_time,
})
|
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/uvindexapi30/uvindex.py#L111-L121
|
map to json
|
python
|
def obj_to_json(self, file_path=None, indent=2, sort_keys=False,
quote_numbers=True):
"""
This will return a str of a json list.
:param file_path: path to data file, defaults to
self's contents if left alone
:param indent: int if set to 2 will indent to spaces and include
line breaks.
:param sort_keys: sorts columns as oppose to column order.
:param quote_numbers: bool if True will quote numbers that are strings
:return: string representing the grid formation
of the relevant data
"""
data = [row.obj_to_ordered_dict(self.columns) for row in self]
if not quote_numbers:
for row in data:
for k, v in row.items():
if isinstance(v, (bool, int, float)):
row[k] = str(row[k])
ret = json.dumps(data, indent=indent, sort_keys=sort_keys)
if sys.version_info[0] == 2:
ret = ret.replace(', \n', ',\n')
self._save_file(file_path, ret)
return ret
|
https://github.com/SeabornGames/Table/blob/0c474ef2fb00db0e7cf47e8af91e3556c2e7485a/seaborn_table/table.py#L680-L704
|
map to json
|
python
|
def to_json(self):
"""
Returns a json-compatible object from the objective that can be saved using the json module.
Example
--------
>>> import json
>>> with open("path_to_file.json", "w") as outfile:
>>> json.dump(obj.to_json(), outfile)
"""
json_obj = {
"name": self.name,
"expression": expr_to_json(self.expression),
"direction": self.direction
}
return json_obj
|
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L921-L936
|
map to json
|
python
|
def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['sub_1'] = self.sub_address_1
json_dict['sub_2'] = self.sub_address_2
json_dict['sub_3'] = self.sub_address_3
json_dict['sub_4'] = self.sub_address_4
return json.dumps(json_dict)
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/messages/module_subtype.py#L50-L59
|
map to json
|
python
|
def to_json_str(self):
"""Convert data to json string representation.
Returns:
json representation as string.
"""
adict = dict(vars(self), sort_keys=True)
adict['type'] = self.__class__.__name__
return json.dumps(adict)
|
https://github.com/PythonSanSebastian/docstamp/blob/b43808f2e15351b0b2f0b7eade9c7ef319c9e646/docstamp/model.py#L62-L70
|
map to json
|
python
|
def to_json(data):
"""Return data as a JSON string."""
return json.dumps(data, default=lambda x: x.__dict__, sort_keys=True, indent=4)
|
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/utils.py#L30-L32
|
map to json
|
python
|
def to_JSON(self):
"""Dumps object fields into a JSON formatted string
:returns: the JSON string
"""
return json.dumps({"station_ID": self._station_ID,
"interval": self._interval,
"reception_time": self._reception_time,
"measurements": self._measurements
})
|
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/stationhistory.py#L111-L121
|
map to json
|
python
|
def to_json(self, data):
"""
Converts the given object to a pretty-formatted JSON string
:param data: the object to convert to JSON
:return: A pretty-formatted JSON string
"""
# Don't forget the empty line at the end of the file
return (
json.dumps(
data,
sort_keys=True,
indent=4,
separators=(",", ": "),
default=self.json_converter,
)
+ "\n"
)
|
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L665-L682
|
map to json
|
python
|
def to_JSON(self):
"""Dumps object fields into a JSON formatted string
:returns: the JSON string
"""
return json.dumps({"reference_time": self._reference_time,
"location": json.loads(self._location.to_JSON()),
"interval": self._interval,
"co_samples": self._co_samples,
"reception_time": self._reception_time,
})
|
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/pollutionapi30/coindex.py#L129-L140
|
map to json
|
python
|
def _get_json_obj(self, endpoint, query, is_post=False):
"""
Return False if connection could not be made.
Otherwise, return a response object from JSON.
"""
response = self._get_response(endpoint, query, is_post=is_post)
content = response.text
try:
return loads(content)
except ValueError:
raise Exception('Could not decode content to JSON:\n%s'
% self.__class__.__name__, content)
|
https://github.com/azavea/python-omgeo/blob/40f4e006f087dbc795a5d954ffa2c0eab433f8c9/omgeo/services/base.py#L155-L166
|
map to json
|
python
|
def to_json(self, *args, **kwargs):
"""
Generate a schema and convert it directly to serialized JSON.
:rtype: ``str``
"""
return json.dumps(self.to_schema(), *args, **kwargs)
|
https://github.com/wolverdude/GenSON/blob/76552d23cf9202e8e7c262cb018eb3cb3df686b9/genson/schema/builder.py#L76-L82
|
map to json
|
python
|
def to_JSON(self):
"""Dumps object fields into a JSON formatted string
:returns: the JSON string
"""
return json.dumps({'name': self._name,
'coordinates': {'lon': self._lon,
'lat': self._lat
},
'ID': self._ID,
'country': self._country})
|
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/location.py#L105-L116
|
map to json
|
python
|
def to_json(self):
""" Creates a JSON serializable representation of this instance
Returns:
:obj:`dict`: For example,
{
"lat": 9.3470298,
"lon": 3.79274,
"time": "2016-07-15T15:27:53.574110"
}
"""
return {
'lat': self.lat,
'lon': self.lon,
'time': self.time.isoformat() if self.time is not None else None
}
|
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/point.py#L118-L133
|
map to json
|
python
|
def json(self):
"""
Return JSON representation of object.
"""
data = {}
for item in self._data:
if isinstance(self._data[item], filetree):
data[item] = self._data[item].json()
else:
data[item] = self._data[item]
return data
|
https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L648-L658
|
map to json
|
python
|
def json_string(self):
"""
Return a JSON representation of the sync map.
:rtype: string
.. versionadded:: 1.3.1
"""
def visit_children(node):
""" Recursively visit the fragments_tree """
output_fragments = []
for child in node.children_not_empty:
fragment = child.value
text = fragment.text_fragment
output_fragments.append({
"id": text.identifier,
"language": text.language,
"lines": text.lines,
"begin": gf.time_to_ssmmm(fragment.begin),
"end": gf.time_to_ssmmm(fragment.end),
"children": visit_children(child)
})
return output_fragments
output_fragments = visit_children(self.fragments_tree)
return gf.safe_unicode(
json.dumps({"fragments": output_fragments}, indent=1, sort_keys=True)
)
|
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/__init__.py#L248-L274
|
map to json
|
python
|
def to_json(self):
"""
Returns a json-compatible object from the Variable that can be saved using the json module.
Example
--------
>>> import json
>>> with open("path_to_file.json", "w") as outfile:
>>> json.dump(var.to_json(), outfile)
"""
json_obj = {
"name": self.name,
"lb": self.lb,
"ub": self.ub,
"type": self.type
}
return json_obj
|
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L317-L333
|
map to json
|
python
|
def json(self, data):
"""
Encodes the dictionary being passed to JSON and sets the Header to application/json
"""
self.write(json_.encode(data))
self.set_header('Content-type', 'application/json')
|
https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/controller.py#L182-L187
|
map to json
|
python
|
def to_json(self):
"""
Returns the JSON representation of the resource.
"""
result = {
'sys': {}
}
for k, v in self.sys.items():
if k in ['space', 'content_type', 'created_by',
'updated_by', 'published_by']:
v = v.to_json()
if k in ['created_at', 'updated_at', 'deleted_at',
'first_published_at', 'published_at', 'expires_at']:
v = v.isoformat()
result['sys'][camel_case(k)] = v
return result
|
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L157-L174
|
map to json
|
python
|
def _parse_json(s):
' parse str into JsonDict '
def _obj_hook(pairs):
' convert json object to python object '
o = JsonDict()
for k, v in pairs.iteritems():
o[str(k)] = v
return o
return json.loads(s, object_hook=_obj_hook)
|
https://github.com/michaelliao/sinaweibopy/blob/0f19dd71c1fbd16ee539620c7e9e986887f5c665/weibo.py#L46-L55
|
map to json
|
python
|
def to_json(self, path, points=50, meta=None):
"""
Write the results of the fit to a json file at `path`.
`points` will define the length of the `fit` array.
If `meta` is given, a `meta` key be added with the given value.
The json object has the form
#!text
{
'data': [ [x1, y1], [x2, y2], ... ],
'fit': [ [x1, y1], [x2, y2], ... ],
'meta': meta
}
"""
pointspace = self.pointspace(num=points)
fit_points = numpy.dstack(pointspace['fit'])[0]
data_points = numpy.dstack(pointspace['data'])[0]
fit = [ [ point[0], point[1] ] for point in fit_points ]
data = [ [ point[0], point[1] ] for point in data_points ]
obj = {'data': data, 'fit': fit}
if meta: obj['meta'] = meta
f = open(path, 'w')
json.dump(obj, f)
f.close
|
https://github.com/razor-x/scipy-data_fitting/blob/c756a645da8629699b3f22244bfb7d5d4d88b179/scipy_data_fitting/fit.py#L775-L804
|
map to json
|
python
|
def map_query_string(self):
"""Maps the GET query string params the the query_key_mapper dict and
updates the request's GET QueryDict with the mapped keys.
"""
if (not self.query_key_mapper or
self.request.method == 'POST'):
# Nothing to map, don't do anything.
# return self.request.POST
return {}
keys = list(self.query_key_mapper.keys())
return {self.query_key_mapper.get(k) if k in keys else k: v.strip()
for k, v in self.request.GET.items()}
|
https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/views/mixins/query.py#L40-L53
|
map to json
|
python
|
def jsonmget(self, path, *args):
"""
Gets the objects stored as a JSON values under ``path`` from
keys ``args``
"""
pieces = []
pieces.extend(args)
pieces.append(str_path(path))
return self.execute_command('JSON.MGET', *pieces)
|
https://github.com/RedisJSON/rejson-py/blob/55f0adf3adc40f5a769e28e541dbbf5377b90ec6/rejson/client.py#L125-L133
|
map to json
|
python
|
def json(self, **kwargs):
"""Decodes response as JSON."""
encoding = detect_encoding(self.content[:4])
value = self.content.decode(encoding)
return simplejson.loads(value, **kwargs)
|
https://github.com/davidwtbuxton/notrequests/blob/e48ee6107a58c2f373c33f78e3302608edeba7f3/notrequests.py#L121-L126
|
map to json
|
python
|
def get_json(self, force=False, silent=False, cache=True):
"""Parse :attr:`data` as JSON.
If the mimetype does not indicate JSON
(:mimetype:`application/json`, see :meth:`is_json`), this
returns ``None``.
If parsing fails, :meth:`on_json_loading_failed` is called and
its return value is used as the return value.
:param force: Ignore the mimetype and always try to parse JSON.
:param silent: Silence parsing errors and return ``None``
instead.
:param cache: Store the parsed JSON to return for subsequent
calls.
"""
if cache and self._cached_json[silent] is not Ellipsis:
return self._cached_json[silent]
if not (force or self.is_json):
return None
data = self._get_data_for_json(cache=cache)
try:
rv = self.json_module.loads(data)
except ValueError as e:
if silent:
rv = None
if cache:
normal_rv, _ = self._cached_json
self._cached_json = (normal_rv, rv)
else:
rv = self.on_json_loading_failed(e)
if cache:
_, silent_rv = self._cached_json
self._cached_json = (rv, silent_rv)
else:
if cache:
self._cached_json = (rv, rv)
return rv
|
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/json.py#L94-L137
|
map to json
|
python
|
def _to_json(self, include_references=True):
"""Convert the model to JSON using the PotionJSONEncode and automatically
resolving the resource as needed (`_properties` call handles this).
"""
if include_references:
return json.dumps(self._resource._properties, cls=PotionJSONEncoder)
else:
return json.dumps(
{
k: v
for k, v in self._resource._properties.items()
if not isinstance(v, Resource) and not k.startswith("$")
},
cls=PotionJSONEncoder,
)
|
https://github.com/onecodex/onecodex/blob/326a0a1af140e3a57ccf31c3c9c5e17a5775c13d/onecodex/models/__init__.py#L345-L359
|
map to json
|
python
|
def json(self, *, # type: ignore
loads: Callable[[Any], Any]=json.loads) -> None:
"""Return parsed JSON data.
.. versionadded:: 0.22
"""
return loads(self.data)
|
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/http_websocket.py#L85-L91
|
map to json
|
python
|
def to_json(self):
"""
Serialize object to json dict
:return: dict
"""
res = dict()
res['Handle'] = ''
res['Name'] = self.name
res['ImageUrl'] = self.url
res['Description'] = self.desc
res["EntityOptions"] = self.options
return res
|
https://github.com/chatfirst/chatfirst/blob/11e023fc372e034dfd3417b61b67759ef8c37ad6/chatfirst/models.py#L87-L99
|
map to json
|
python
|
def prepare_roomMap(roomMap):
""" Prepares the roomMap to be JSONified. That is: convert the non
JSON serializable objects such as set() """
ret = {}
for room in roomMap:
ret[room] = [roomMap[room].name, list(roomMap[room].pcs)]
return ret
|
https://github.com/bwesterb/tkbd/blob/fcf16977d38a93fe9b7fa198513007ab9921b650/src/cometApi.py#L7-L13
|
map to json
|
python
|
def json_data(self, instance, default=None):
"""Get a JSON compatible value
"""
value = self.get(instance)
out = []
for rel in value:
if rel.isBroken():
logger.warn("Skipping broken relation {}".format(repr(rel)))
continue
obj = rel.to_object
out.append(api.get_url_info(obj))
return out
|
https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/fieldmanagers.py#L201-L213
|
map to json
|
python
|
def to_json(self, minimal=True):
"""Encode an object as a JSON string.
:param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections)
:rtype: str
"""
if minimal:
return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True)
else:
return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True)
|
https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/base.py#L45-L55
|
map to json
|
python
|
def to_json(self):
"""
Returns the JSON Representation of the resource.
"""
result = super(FieldsResource, self).to_json()
result['fields'] = self.fields_with_locales()
return result
|
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L290-L297
|
map to json
|
python
|
def to_json(self, indent=2):
""" Return self formatted as JSON. """
return json.dumps(self, default=json_encode_for_printing, indent=indent)
|
https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/api_objects/__init__.py#L52-L54
|
map to json
|
python
|
def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['closed'] = self.closed
json_dict['enabled'] = self.enabled
json_dict['normal'] = self.normal
json_dict['locked'] = self.locked
return json.dumps(json_dict)
|
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/messages/module_status.py#L85-L94
|
map to json
|
python
|
def from_json(cls, json):
"""Create new MapreduceSpec from the json, encoded by to_json.
Args:
json: json representation of MapreduceSpec.
Returns:
an instance of MapreduceSpec with all data deserialized from json.
"""
mapreduce_spec = cls(json["name"],
json["mapreduce_id"],
json["mapper_spec"],
json.get("params"),
json.get("hooks_class_name"))
return mapreduce_spec
|
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/model.py#L518-L532
|
map to json
|
python
|
def json_to_file(data, filename, pretty=False):
'''Dump JSON data to a file'''
kwargs = dict(indent=4) if pretty else {}
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
dump = json.dumps(api.__schema__, **kwargs)
with open(filename, 'wb') as f:
f.write(dump.encode('utf-8'))
|
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/commands.py#L24-L32
|
map to json
|
python
|
def json_data(self, instance, default=None):
"""Get a JSON compatible value
"""
value = self.get(instance)
return value or default
|
https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/fieldmanagers.py#L40-L44
|
map to json
|
python
|
def read_emote_mappings(json_obj_files=[]):
""" Reads the contents of a list of files of json objects and combines
them into one large json object. """
super_json = {}
for fname in json_obj_files:
with open(fname) as f:
super_json.update(json.loads(f.read().decode('utf-8')))
return super_json
|
https://github.com/d6e/emotion/blob/8ea84935a9103c3079579b3d9b9db85e12710af2/emote/emote.py#L9-L16
|
map to json
|
python
|
def read_json (self, mode='rt', **kwargs):
"""Use the :mod:`json` module to read in this file as a JSON-formatted data
structure. Keyword arguments are passed to :func:`json.load`. Returns the
read-in data structure.
"""
import json
with self.open (mode=mode) as f:
return json.load (f, **kwargs)
|
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/io.py#L791-L800
|
map to json
|
python
|
def store_json(obj, destination):
"""store_json
Takes in a json-portable object and a filesystem-based destination and stores
the json-portable object as JSON into the filesystem-based destination.
This is blind, dumb, and stupid; thus, it can fail if the object is more
complex than simple dict, list, int, str, etc. type object structures.
"""
with open(destination, 'r+') as FH:
fcntl.lockf(FH, fcntl.LOCK_EX)
json_in = json.loads(FH.read())
json_in.update(obj) # obj overwrites items in json_in...
FH.seek(0)
FH.write(json.dumps(json_in, sort_keys=True, indent=4,
separators=(',', ': ')))
|
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5-sdk-dist/build_pkgs.py#L351-L366
|
map to json
|
python
|
def json_data(self, instance, default=None):
"""Get a JSON compatible value
"""
value = self.get(instance)
if value:
return value.output
return value
|
https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/fieldmanagers.py#L114-L120
|
map to json
|
python
|
def map_input_output(item, api):
"""
Maps item to appropriate sevebridges object.
:param item: Input/Output value.
:param api: Api instance.
:return: Mapped object.
"""
if isinstance(item, list):
return [map_input_output(it, api) for it in item]
elif isinstance(item, dict) and 'class' in item:
if item['class'].lower() == 'file':
return File(id=item['path'], api=api)
else:
return item
|
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/models/compound/tasks/__init__.py#L4-L19
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.