-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathjsongraph3.py
More file actions
executable file
·186 lines (133 loc) · 4.47 KB
/
jsongraph3.py
File metadata and controls
executable file
·186 lines (133 loc) · 4.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""JSON Graph Python Library
Parameters
----------
None
Returns
-------
None
Long Description
"""
import io
import json
import os.path
import ssl
import sys
import urllib.error
import urllib.parse
import urllib.request
from jsonschema import Draft4Validator
from objects.edge import Edge
from objects.graph import Graph
from objects.multigraph import Multigraph
from objects.node import Node # TODO add in original
ssl._create_default_https_context = ssl._create_unverified_context
def load_json_string(jsonstring):
"""Check if string is JSON and if so return python dictionary"""
try:
json_object = json.loads(jsonstring)
except ValueError as e:
return False
return json_object
def get_github_masterschema():
"""Read JSON Graph Schema file from Github Master branch"""
link = "https://raw.githubusercontent.com/jsongraph/json-graph-specification/master/json-graph-schema_v2.json"
f = urllib.request.urlopen(link)
js = json.load(f)
f.close
return js
def get_json(jsongraph):
"""Check if parameter is a file object, filepath or JSON string
Return: dictionary object OR False for failure
"""
if type(jsongraph) is dict:
return jsongraph
elif isinstance(jsongraph, io.IOBase):
return json.load(jsongraph)
elif os.path.isfile(jsongraph):
with open(jsongraph, "rb") as f:
return json.load(f)
jg = load_json_string(jsongraph)
if jg:
return jg
else:
return False
def validate_schema(schema="", verbose=False):
"""Validate schema file"""
if not schema:
schema = get_github_masterschema()
else:
schema = get_json(schema)
results = Draft4Validator.check_schema(schema)
if verbose and results:
print(" Schema doesn't validate!")
print(results)
elif verbose:
print(" Schema Validates!")
if results:
return (False, results)
return (True, "")
def validate_jsongraph(jsongraph, schema="", verbose=False):
"""Validate JSON Graph against given jsongraph object and schema object"""
jg = get_json(jsongraph)
if not schema:
schema = get_github_masterschema()
else:
schema = get_json(schema)
if not jg:
sys.exit(
"JSON Graph parameter does not appear to be a file object, filepath or JSON string."
)
if not schema:
sys.exit(
"JSON Graph Schema parameter does not appear to be a file object, filepath or JSON string."
)
schema = Draft4Validator(schema) # transform schema in a Schema validation object
errors = [error for error in schema.iter_errors(jg)]
if verbose and errors:
print("Problem with JSON Graph")
for error in errors:
print(error)
quit()
elif verbose:
print(" Validated!")
if errors:
return errors
return (True, "")
def load_graphs(jsongraphs, validate=False, schema="", verbose=False):
"""Loads one or more graphs from jsongraphs JSON as a generator"""
jgs = get_json(jsongraphs)
if validate:
(status, results) = validate_jsongraph(jsongraphs, schema, verbose)
sys.exit("JSON Graph does not validate")
if "graph" in jgs:
yield jgs["graph"]
if "graphs" in jgs:
for graph in jgs["graphs"]:
yield graph
def test_example_graphs():
"""Test and usage example"""
single_graph_link = "https://raw.githubusercontent.com/jsongraph/json-graph-specification/master/examples/usual_suspects.json"
multiple_graph_link = "https://raw.githubusercontent.com/jsongraph/json-graph-specification/master/examples/car_graphs.json"
f = urllib.request.urlopen(single_graph_link)
sg = json.load(f)
f.close
f = urllib.request.urlopen(multiple_graph_link)
mg = json.load(f)
f.close
print("Does JSON Graph Schema validate?")
validate_schema(schema="", verbose=True)
print("\nDoes Single Graph example validate?")
validate_jsongraph(sg, schema="", verbose=True)
print("\nShow Label of Single Graph")
graphs = load_graphs(sg, validate=False, schema="", verbose=False)
print(" Label: ", next(graphs)["label"])
print("\nShow Label's of Multiple Graphs")
graphs = load_graphs(mg, validate=False, schema="", verbose=False)
for graph in graphs:
print(" Label: ", graph["label"])
def main():
test_example_graphs()
if __name__ == "__main__":
main()