python中json引用的实现
jsonref-ap的Python项目详细描述
jsonref是用于自动取消引用 JSON Reference python的对象(支持2.6+包括python 3)。
这个库允许您对json引用对象使用数据结构,就像 引用已替换为引用数据。
>>>frompprintimportpprint>>>importjsonref>>># An example json document>>>json_str="""{"real": [1, 2, 3, 4], "ref": {"$ref": "#/real"}}""">>>data=jsonref.loads(json_str)>>>pprint(data)# Reference is not evaluated until here{'real':[1,2,3,4],'ref':[1,2,3,4]}
功能
- 参考文献的评估很慢。在使用之前,任何内容都不会被取消引用。
- 支持递归引用,并创建递归python数据 结构。
引用对象实际上被惰性查找代理对象替换,这些对象是 几乎完全透明。
>>>data=jsonref.loads('{"real": [1, 2, 3, 4], "ref": {"$ref": "#/real"}}')>>># You can tell it is a proxy by using the type function>>>type(data["real"]),type(data["ref"])(<class'list'>, <class 'jsonref.JsonRef'>)>>># You have direct access to the referent data with the __subject__>>># attribute>>>type(data["ref"].__subject__)<class'list'>>>># If you need to get at the reference object>>>data["ref"].__reference__{'$ref':'#/real'}>>># Other than that you can use the proxy just like the underlying object>>>ref=data["ref"]>>>isinstance(ref,list)True>>>data["real"]==refTrue>>>ref.append(5)>>>delref[0]>>># Actions on the reference affect the real data (if it is mutable)>>>pprint(data){'real':[2,3,4,5],'ref':[2,3,4,5]}