#!/usr/bin/env python # coding: utf-8 # # JSON Conversions # # This notebook demonstrates how to [convert](https://nexus-forge.readthedocs.io/en/latest/interaction.html#converting) a [Resource](https://nexus-forge.readthedocs.io/en/latest/interaction.html#resource) to JSON and vice-versa. # In[ ]: from kgforge.core import KnowledgeGraphForge # A configuration file is needed in order to create a KnowledgeGraphForge session. A configuration can be generated using the notebook [00-Initialization.ipynb](00%20-%20Initialization.ipynb). # In[ ]: forge = KnowledgeGraphForge("../../configurations/forge.yml") # ## Imports # In[ ]: import json # In[ ]: from kgforge.core import Resource # In[ ]: def pp(x): print(json.dumps(x, indent=4)) # ## Resource to JSON # In[ ]: address = Resource(type="PostalAddress", country="Switzerland", locality="Geneva") # In[ ]: jane = Resource(type="Person", name="Jane Doe", address=address) # In[ ]: john = Resource(type="Person", name="John Smith", email="john.smith@epfl.ch") # In[ ]: persons = [jane, john] # In[ ]: forge.register(persons) # In[ ]: association = Resource(type="Association", agent=persons) # In[ ]: forge.register(association) # In[ ]: pp(forge.as_json(association)) # In[ ]: pp(forge.as_json(association, store_metadata=True)) # ## JSON to Resource # In[ ]: address = Resource(type="PostalAddress", country="Switzerland", locality="Geneva") # In[ ]: jane = Resource(type="Person", name="Jane Doe", address=address) # In[ ]: john = Resource(type="Person", name="John Smith", email="john.smith@epfl.ch") # In[ ]: persons = [jane, john] # In[ ]: association = Resource(type="Association", agent=[jane, john]) # In[ ]: data = { "type": "Association", "agent": [ { "type": "Person", "address": { "type": "PostalAddress", "country": "Switzerland", "locality": "Geneva", }, "email": "(missing)", "name": "Jane Doe" }, { "type": "Person", "email": "john.smith@epfl.ch", "name": "John Smith" } ] } # In[ ]: resource = forge.from_json(data, na="(missing)") # In[ ]: resource == association