def DumpJson(data): """Returns textual JSON from data""" #NOTE(g): Import is done here, instead of the top of the file, to not require this module if it is not used import json text = yaml.dumps(data) return text
def write_to_file(self, fd, fmt): data = self.dump_model() if fmt == 'yaml': output = yaml.safe_dump(data, default_flow_style=False) else: output = yaml.dumps(data, indent=2) fd.write(output) if not fd == sys.stdout: fd.close()
def list_proxies_filtered(): blocked_id = request.args.get('blocked', 'None') if blocked_id != 'None': print "Got a blocked URL back from the scraper: %s" % blocked_id for entry in proxy_list['proxy_list']: #print "Checking: %s and %s" % ( entry['id'], blocked_id ) if str(entry['id']) == str(blocked_id): print "Told to disable %s" % blocked_id entry['enabled'] = False entry['working'] = False if request.args.get('json', True) is False: return yaml.dumps( strip_proxy_list(proxy_list) ) else: return json.dumps( strip_proxy_list(proxy_list) )
def imp(): a2z = {} with open("Raw.txt", "r") as f: contents = f.read() lines = contents.split("\n") for raw_line in lines: line = raw_line.strip() if "–" in line: parts = line.split("–") if len(parts) > 1: # strp sparts = stripped(parts) print sparts term = sparts[0] az = sparts[0][0].lower() if not az in a2z: a2z[az] = {} defs = sparts[1:] a2z[az] [term] = dict(defs=defs) else: #print " ??:", parts pass else: #print " ?:", line pass print a2z.keys() ## Now we serialse to yaml for a_char in a2z: dir_path = ROOT + a_char print "=", dir_path if not os.path.exists(dir_path): os.makedirs(dir_path) data = a2z[a_char] yaml_str = yaml.dumps(data) file_name = a.replace(" ", "_") + ".yaml" print file_name
def encode_content_data(data, mime_type='application/python-pickle', transfer_encoding='BASE64'): content = {} if data is not None: if mime_type == 'application/python-pickle': # Pickle object. content['data'] = pickle.dumps(data, protocol=-1) elif mime_type == 'application/x-yaml': content['data'] = yaml.dumps(data) elif mime_type is None or mime_type in ('application/octet-stream', 'application/json', 'text/plain'): content['data'] = data # Encode content data as base64, if necessary. # # [1]: https://www.w3.org/Protocols/rfc1341/5_Content-Transfer-Encoding.html if transfer_encoding == 'BASE64': content['data'] = base64.b64encode(content['data']) if mime_type is not None: content['metadata'] = {'mime_type': mime_type} return content
def obj_to_yaml(obj): """ obj > yamlstring """ return yaml.dumps(obj)
def dumps(self): """Dump a yaml object as a string.""" return yaml.dumps(self.yamlObj)
except ImportError: has_yaml = False """Whether the :py:mod:`yaml` module is available or not.""" else: has_yaml = True try: from yaml import CLoader as Loader, CDumper as Dumper except ImportError: from yaml import Loader, Dumper SERIALIZER_DRIVERS = {} """The serializer drivers that are available.""" SERIALIZER_DRIVERS['json'] = {'load': json.load, 'dumps': lambda obj: json.dumps(obj, sort_keys=True, indent=4)} SERIALIZER_DRIVERS['jsn'] = {'load': json.load, 'dumps': lambda obj: json.dumps(obj, sort_keys=True, indent=4)} if has_yaml: SERIALIZER_DRIVERS['yaml'] = {'load': lambda file_obj: yaml.load(file_obj, Loader=Loader), 'dumps': lambda obj: yaml.dumps(obj, default_flow_style=False, Dumper=Dumper)} SERIALIZER_DRIVERS['yml'] = {'load': lambda file_obj: yaml.load(file_obj, Loader=Loader), 'dumps': lambda obj: yaml.dumps(obj, default_flow_style=False, Dumper=Dumper)} class MemoryConfiguration(object): """ This class provides an interface for retrieving values from deeply nested objects supporting Python's __getitem__ interface. """ seperator = '.' def __init__(self, mem_object, prefix=''): """ :param smem_object: The memory object to parse. :param str prefix: String to be prefixed to all option names. :param str object_type: String to identify how to parse the mem_object. """ self.prefix = prefix
def main(): ident = sys.argv[1] cmdb_data = getHost(ident) if cmdb_data['status'] == 0: data = {'classes': [str(i) for i in cmdb_data['data']['hostgroups']]} print yaml.dumps(data, explicit_start=True, default_flow_style=False)
@classmethod def load(self, filepath): '''Open and read from named file. Return deserialized contents.''' file_ending = filepath.split('.')[-1].lower() specialist = self._get(file_ending) with open(filepath, encoding='utf-8') as filelike_object: return specialist.load(filelike_object) @classmethod def dumps(self, data, format='json'): '''Return a string.''' specialist = self._get(format) return specialist.dumps(data) ############ # EXAMPLES # ############ JSON = Serialization(('json',), lambda f: json.load(f), lambda f: json.dumps(f)) if yaml: YAML = Serialization(('yaml', 'yml'), lambda f: yaml.load(f), lambda f: yaml.dumps(f))
def results_to_yaml(query, results): yield yaml.dumps(results) yield "---"
def to_yaml(self): """ Convert this TSR chain to a YAML string. """ import yaml return yaml.dumps(self.to_dict())
def json2yaml(JsonFilePath, YamlFilePath): pdm = load_json_from_file(JsonFilePath) y = open(YamlFilePath, "w") y.write(yaml.dumps(pdm))
def dump_proxy(obj, **args): """ monkey patch json to look like yaml """ return yaml.dumps(obj)
def write_yaml(name, value): print(yaml.dumps({name:value}))
import yaml person = {"name": "foo", "age": 20} print(yaml.dumps(person)) # list print(yaml.dumps([person]))
def dumps(cls, obj, fp, *args, **kwargs): try: return yamllib.dumps(obj, fp, *args, **kwargs) except Exception, e: raise TranscoderDumpException(e)