26
loading...
This website collects cookies to deliver better user experience
json.dumps(dict, indent=4)
is pretty handy for previewing what your code thinks structured data looks like. Technically this is possible with YAML, but conventions on, say, a string
literal can be squishy.
name: True
could be interpreted as:"name": true
, indicating a Boolean value"name": "True"
, indicating a Stringjson.dumps(dict, indent=4)
for outputs. You'll pick it up in about half an hour and just passively get better over time.Element
and ElementTree
constructs are more nuanced than dictionaries, so a package like defusedXML
is probably the best way to get started. There are a lot of binary invocations/security issues with XML, so using basic XML libraries by themselves is ill-advised. xmltodict is pretty handy if you just want to convert it into another format.ruamel.YAML
library, which adds on some interesting capabilities when parsing human inputs. I've found a nifty way to parse using try
/except
blocks - making a parser that is supremely agnostic, ingesting JSON or YAML , as a string or a file!--------message: items: item: "@tag": Blue "#text": Hello, World!
#!/usr/bin/python3import jsonfrom ruamel.yaml import YAMLfrom ruamel.yaml import scanner# Load Definition Classesyaml_input = YAML(typ='safe')yaml_dict = {}# Input can take a file first, but will fall back to YAML processing of a stringtry: yaml_dict = yaml_input.load(open('example.yml', 'r'))except FileNotFoundError: print('Not found as file, trying as a string...') yaml_dict = yaml_input.load('example.yml')finally: print(json.dumps(yaml_dict, indent=4))
{ "message": { "items": { "item": { "@tag": "Blue", "#text": "Hello, World!" } } }}
#!/usr/bin/python3import jsonwith open('example.json', 'r') as file: print(json.dumps(json.loads(file.read())))
json.dumps(dict, indent=4)
on a live dict
when I'm done with it - dumping it to a file. JSON is a well-defined standard and software support for it is excellent.grep
users everywhere.Element
and ElementTree
constructs in Python instead of dicts
. This is due to XML being capable of so much more, but it's still pretty easy to use:<?xml version="1.0" encoding="ISO-8859-1" ?><message> <items> <item tag="Blue">Hello, World!</item> </items></message>
#!/usr/bin/python3from defusedxml.ElementTree import parseimport xmltodictimport jsondocument = parse('example.xml').getroot()print(document[0][0].text + " " + json.dumps(document[0][0].attrib))file = open('example.xml', "r").read()print(json.dumps(xmltodict.parse(file), indent=4))
xmltodict
for data processing - it lets me use a common language, Python lists
and dicts
to process all data regardless of source, allowing me to focus more on the payload. We're really fortunate to have this fantastic F/OSS community enabling that!