sku: !!python/object/new:bson.objectid.ObjectId
state: !!binary |
VZ3yU14L3F0zUWxT sku: !!python/object/new:bson.objectid.ObjectId ['5694992601f5b45ecebfeacb']
sku_seoncd: !!python/object/new:bson.objectid.ObjectId
oid: '5694992601f5b45ecebfeacb'
Hi Peng Dai,
Using pyyaml you can define custom tags. You can register custom constructors and representers using the functions yaml.add_constructor and yaml.add_representer.
As an example, given Python dictionary which contain an ObjectId() object like below:
{ "_id" : ObjectId("5695d388f11a8aea9fd322b7"),
"a" : 1, "b" : 1, "c" : 1 }
First you define a representer that converts an ObjectId() to a scalar node, then register it using yaml.add_representer:
def objectid_representer(dumper, data):
return dumper.represent_scalar("!bson.objectid.ObjectId", str(data))
yaml.SafeDumper.add_representer(objectid.ObjectId, objectid_representer)
yaml.safe_dump(doc_with_objectid, yamlfile, default_flow_style=False)
The resulting yaml file content would look like :
_id: !bson.objectid.ObjectId '5695d388f11a8aea9fd322b7'
a: 1.0
b: 1.0
c: 1.0
To load it back in as an ObjectId(), register a constructor for the tag:
def objectid_constructor(loader, data):
return objectid.ObjectId(loader.construct_scalar(data))
yaml.add_constructor('!bson.objectid.ObjectId', objectid_constructor)
loaded = yaml.load(open(yamlfile, 'r'))
For the full example script see github gist: ObjectID_YAML.py.
Regards,
Wan.