how to write the ObjectId object in yaml file.

381 views
Skip to first unread message

Peng Dai

unread,
Jan 12, 2016, 1:39:00 AM1/12/16
to mongodb-user
when write the unit test for my web API. I usually need to init some db data.
I choose the YAML other than JSON, cause it is much easy to read and write.

the problem is I cannot write the ObjectId by hand.
If I use the ```yaml.dump``` to generate the result. it would looks like:
    sku: !!python/object/new:bson.objectid.ObjectId
      state
: !!binary |
        VZ3yU14L3F0zUWxT

this is really hard to me, I check the yaml help and some blog. It seems I can write it like this:

  sku: !!python/object/new:bson.objectid.ObjectId ['5694992601f5b45ecebfeacb']
  sku_seoncd
: !!python/object/new:bson.objectid.ObjectId
    oid
: '5694992601f5b45ecebfeacb'

but both the two style not work at all. So what's the right way to write the ObjectId object in a readable way to the yaml file?

Wan Bachtiar

unread,
Jan 13, 2016, 2:25:39 AM1/13/16
to mongodb-user

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.

Reply all
Reply to author
Forward
0 new messages