gazpachoking/jsonref

Feature Request: when serializing, replace references with referents.

Closed this issue · 3 comments

This is a feature request, but first of all: Thanks for making jsonref. It's handy.


From the documentation:

dump() and dumps() work just like their json counterparts, except they output the original reference objects when encountering JsonRef instances.

I was a bit unclear whether the "original reference object" was the reference itself, versus the object being referred to. I had hoped it was the latter, but it turned out to be the former.

Confirmed by this experiment

import jsonref
print(jsonref.dumps(jsonref.loads('''
{
  "foo": {
    "$ref": "#/def/obj"
  },
  "def": {
    "obj": {
      "bar": "baz"
    }
  }
}
''')))

Output references (this is what happens):

{"foo": {"$ref": "#/def/obj"}, "def": {"obj": {"bar": "baz"}}}:

Output objects referred to (this is what I hoped for):

{"foo": {"bar" : "baz"}, "def": {"obj": {"bar": "baz"}}}:

I found a way to get what I want here, but maybe this could be optional built-in functionality? Perhaps like this:

jsonref.dumps(obj, references_as='values') 

I had exactly the same problem. Your workarround helped me a lot!
Thanks!

Another relatively simple workaround using the "default" argument of json.dumps in combination with JsonRef.__subject__:

import jsonref
import json

json_data = '{"x": {"$ref": "#/y"}, "y": "abc"}'

def default_for_jsonref(o):
    if isinstance(o, jsonref.JsonRef):
        return o.__subject__

print(json.dumps(jsonref.loads(json_data), default=default_for_jsonref))
# ^ yields '{"x": "abc", "y": "abc"}'

You can turn proxies mode off in 1.0.0