jsonld.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. """
  2. This parser will interpret a JSON-LD document as an RDF Graph. See http://json-ld.org/
  3. Example:
  4. ```python
  5. >>> from rdflib import Graph, URIRef, Literal
  6. >>> test_json = '''
  7. ... {
  8. ... "@context": {
  9. ... "dc": "http://purl.org/dc/terms/",
  10. ... "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
  11. ... "rdfs": "http://www.w3.org/2000/01/rdf-schema#"
  12. ... },
  13. ... "@id": "http://example.org/about",
  14. ... "dc:title": {
  15. ... "@language": "en",
  16. ... "@value": "Someone's Homepage"
  17. ... }
  18. ... }
  19. ... '''
  20. >>> g = Graph().parse(data=test_json, format='json-ld')
  21. >>> list(g) == [(URIRef('http://example.org/about'),
  22. ... URIRef('http://purl.org/dc/terms/title'),
  23. ... Literal("Someone's Homepage", lang='en'))]
  24. True
  25. ```
  26. """
  27. # From: https://github.com/RDFLib/rdflib-jsonld/blob/feature/json-ld-1.1/rdflib_jsonld/parser.py
  28. # NOTE: This code reads the entire JSON object into memory before parsing, but
  29. # we should consider streaming the input to deal with arbitrarily large graphs.
  30. from __future__ import annotations
  31. import secrets
  32. import warnings
  33. from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
  34. import rdflib.parser
  35. from rdflib.graph import ConjunctiveGraph, Graph
  36. from rdflib.namespace import RDF, XSD
  37. from rdflib.parser import InputSource, URLInputSource
  38. from rdflib.term import BNode, IdentifiedNode, Literal, Node, URIRef
  39. from ..shared.jsonld.context import UNDEF, Context, Term
  40. from ..shared.jsonld.keys import (
  41. CONTEXT,
  42. GRAPH,
  43. ID,
  44. INCLUDED,
  45. INDEX,
  46. JSON,
  47. LANG,
  48. LIST,
  49. NEST,
  50. NONE,
  51. REV,
  52. SET,
  53. TYPE,
  54. VALUE,
  55. VOCAB,
  56. )
  57. from ..shared.jsonld.util import (
  58. _HAS_ORJSON,
  59. VOCAB_DELIMS,
  60. context_from_urlinputsource,
  61. json,
  62. orjson,
  63. source_to_json,
  64. )
  65. __all__ = ["JsonLDParser", "to_rdf"]
  66. TYPE_TERM = Term(str(RDF.type), TYPE, VOCAB) # type: ignore[call-arg]
  67. ALLOW_LISTS_OF_LISTS = True # NOTE: Not allowed in JSON-LD 1.0
  68. class JsonLDParser(rdflib.parser.Parser):
  69. def __init__(self):
  70. super(JsonLDParser, self).__init__()
  71. def parse(
  72. self,
  73. source: InputSource,
  74. sink: Graph,
  75. version: float = 1.1,
  76. skolemize: bool = False,
  77. encoding: Optional[str] = "utf-8",
  78. base: Optional[str] = None,
  79. context: Optional[
  80. Union[
  81. List[Union[Dict[str, Any], str, None]],
  82. Dict[str, Any],
  83. str,
  84. ]
  85. ] = None,
  86. generalized_rdf: Optional[bool] = False,
  87. extract_all_scripts: Optional[bool] = False,
  88. **kwargs: Any,
  89. ) -> None:
  90. """Parse JSON-LD from a source document.
  91. The source document can be JSON or HTML with embedded JSON script
  92. elements (type attribute = `application/ld+json`). To process as HTML
  93. `source.content_type` must be set to "text/html" or
  94. `application/xhtml+xml.
  95. Args:
  96. source: InputSource with JSON-formatted data (JSON or HTML)
  97. sink: Graph to receive the parsed triples
  98. version: parse as JSON-LD version, defaults to 1.1
  99. skolemize: whether to skolemize blank nodes, defaults to False
  100. encoding: character encoding of the JSON (should be "utf-8"
  101. base: JSON-LD [Base IRI](https://www.w3.org/TR/json-ld/#base-iri), defaults to None
  102. context: JSON-LD [Context](https://www.w3.org/TR/json-ld/#the-context), defaults to None
  103. generalized_rdf: parse as [Generalized RDF](https://www.w3.org/TR/json-ld/#relationship-to-rdf), defaults to False
  104. extract_all_scripts: if source is an HTML document then extract
  105. script element). This is ignored if `source.system_id` contains
  106. a fragment identifier, in which case only the script element with
  107. matching id attribute is extracted.
  108. """
  109. if encoding not in ("utf-8", "utf-16"):
  110. warnings.warn(
  111. "JSON should be encoded as unicode. "
  112. "Given encoding was: %s" % encoding
  113. )
  114. if not base:
  115. base = sink.absolutize(source.getPublicId() or source.getSystemId() or "")
  116. context_data = context
  117. if not context_data and hasattr(source, "url") and hasattr(source, "links"):
  118. if TYPE_CHECKING:
  119. assert isinstance(source, URLInputSource)
  120. context_data = context_from_urlinputsource(source)
  121. try:
  122. version = float(version)
  123. except ValueError:
  124. version = 1.1
  125. # Get the optional fragment identifier
  126. try:
  127. fragment_id = URIRef(source.getSystemId()).fragment
  128. except Exception:
  129. fragment_id = None
  130. data, html_base = source_to_json(source, fragment_id, extract_all_scripts)
  131. if html_base is not None:
  132. base = URIRef(html_base, base=base)
  133. # NOTE: A ConjunctiveGraph parses into a Graph sink, so no sink will be
  134. # context_aware. Keeping this check in case RDFLib is changed, or
  135. # someone passes something context_aware to this parser directly.
  136. conj_sink: Graph
  137. if not sink.context_aware:
  138. conj_sink = ConjunctiveGraph(store=sink.store, identifier=sink.identifier)
  139. else:
  140. conj_sink = sink
  141. to_rdf(
  142. data,
  143. conj_sink,
  144. base,
  145. context_data,
  146. version,
  147. bool(generalized_rdf),
  148. skolemize=skolemize,
  149. )
  150. def to_rdf(
  151. data: Any,
  152. dataset: Graph,
  153. base: Optional[str] = None,
  154. context_data: Optional[
  155. Union[
  156. List[Union[Dict[str, Any], str, None]],
  157. Dict[str, Any],
  158. str,
  159. ]
  160. ] = None,
  161. version: Optional[float] = None,
  162. generalized_rdf: bool = False,
  163. allow_lists_of_lists: Optional[bool] = None,
  164. skolemize: bool = False,
  165. ):
  166. # TODO: docstring w. args and return value
  167. context = Context(base=base, version=version)
  168. if context_data:
  169. context.load(context_data)
  170. parser = Parser(
  171. generalized_rdf=generalized_rdf,
  172. allow_lists_of_lists=allow_lists_of_lists,
  173. skolemize=skolemize,
  174. )
  175. return parser.parse(data, context, dataset)
  176. class Parser:
  177. def __init__(
  178. self,
  179. generalized_rdf: bool = False,
  180. allow_lists_of_lists: Optional[bool] = None,
  181. skolemize: bool = False,
  182. ):
  183. self.skolemize = skolemize
  184. self.generalized_rdf = generalized_rdf
  185. self.allow_lists_of_lists = (
  186. allow_lists_of_lists
  187. if allow_lists_of_lists is not None
  188. else ALLOW_LISTS_OF_LISTS
  189. )
  190. self.invalid_uri_to_bnode: dict[str, BNode] = {}
  191. def parse(self, data: Any, context: Context, dataset: Graph) -> Graph:
  192. topcontext = False
  193. resources: Union[Dict[str, Any], List[Any]]
  194. if isinstance(data, list):
  195. resources = data
  196. elif isinstance(data, dict):
  197. local_context = data.get(CONTEXT)
  198. if local_context:
  199. context.load(local_context, context.base)
  200. topcontext = True
  201. resources = data
  202. # type error: Subclass of "Dict[str, Any]" and "List[Any]" cannot exist: would have incompatible method signatures
  203. if not isinstance(resources, list): # type: ignore[unreachable]
  204. resources = [resources]
  205. if context.vocab:
  206. dataset.bind(None, context.vocab)
  207. for name, term in context.terms.items():
  208. if term.id and term.id.endswith(VOCAB_DELIMS):
  209. dataset.bind(name, term.id)
  210. # type error: "Graph" has no attribute "default_context"
  211. graph = dataset.default_context if dataset.context_aware else dataset # type: ignore[attr-defined]
  212. for node in resources:
  213. self._add_to_graph(dataset, graph, context, node, topcontext)
  214. return graph
  215. def _add_to_graph(
  216. self,
  217. dataset: Graph,
  218. graph: Graph,
  219. context: Context,
  220. node: Any,
  221. topcontext: bool = False,
  222. ) -> Optional[Node]:
  223. if not isinstance(node, dict) or context.get_value(node):
  224. # type error: Return value expected
  225. return # type: ignore[return-value]
  226. if CONTEXT in node and not topcontext:
  227. local_context = node[CONTEXT]
  228. if local_context:
  229. context = context.subcontext(local_context)
  230. else:
  231. context = Context(base=context.doc_base)
  232. # type error: Incompatible types in assignment (expression has type "Optional[Context]", variable has type "Context")
  233. context = context.get_context_for_type(node) # type: ignore[assignment]
  234. id_val = context.get_id(node)
  235. if id_val is None:
  236. nested_id = self._get_nested_id(context, node)
  237. if nested_id is not None and len(nested_id) > 0:
  238. id_val = nested_id
  239. if isinstance(id_val, str):
  240. subj = self._to_rdf_id(context, id_val)
  241. else:
  242. subj = BNode()
  243. if self.skolemize:
  244. subj = subj.skolemize()
  245. if subj is None:
  246. return None
  247. # NOTE: crude way to signify that this node might represent a named graph
  248. no_id = id_val is None
  249. for key, obj in node.items():
  250. if key == CONTEXT or key in context.get_keys(ID):
  251. continue
  252. if key == REV or key in context.get_keys(REV):
  253. for rkey, robj in obj.items():
  254. self._key_to_graph(
  255. dataset,
  256. graph,
  257. context,
  258. subj,
  259. rkey,
  260. robj,
  261. reverse=True,
  262. no_id=no_id,
  263. )
  264. else:
  265. self._key_to_graph(dataset, graph, context, subj, key, obj, no_id=no_id)
  266. return subj
  267. # type error: Missing return statement
  268. def _get_nested_id(self, context: Context, node: Dict[str, Any]) -> Optional[str]: # type: ignore[return]
  269. for key, obj in node.items():
  270. if context.version >= 1.1 and key in context.get_keys(NEST):
  271. term = context.terms.get(key)
  272. if term and term.id is None:
  273. continue
  274. objs = obj if isinstance(obj, list) else [obj]
  275. for obj in objs:
  276. if not isinstance(obj, dict):
  277. continue
  278. id_val = context.get_id(obj)
  279. if not id_val:
  280. subcontext = context.get_context_for_term(
  281. context.terms.get(key)
  282. )
  283. id_val = self._get_nested_id(subcontext, obj)
  284. if isinstance(id_val, str):
  285. return id_val
  286. def _key_to_graph(
  287. self,
  288. dataset: Graph,
  289. graph: Graph,
  290. context: Context,
  291. subj: Node,
  292. key: str,
  293. obj: Any,
  294. reverse: bool = False,
  295. no_id: bool = False,
  296. ) -> None:
  297. if isinstance(obj, list):
  298. obj_nodes = obj
  299. else:
  300. obj_nodes = [obj]
  301. term = context.terms.get(key)
  302. if term:
  303. term_id = term.id
  304. if term.type == JSON:
  305. obj_nodes = [self._to_typed_json_value(obj)]
  306. elif LIST in term.container:
  307. obj_nodes = [self._expand_nested_list(obj_nodes)]
  308. elif isinstance(obj, dict):
  309. obj_nodes = self._parse_container(context, term, obj)
  310. else:
  311. term_id = None
  312. if TYPE in (key, term_id):
  313. term = TYPE_TERM
  314. if GRAPH in (key, term_id):
  315. if dataset.context_aware and not no_id:
  316. if TYPE_CHECKING:
  317. assert isinstance(dataset, ConjunctiveGraph)
  318. # type error: Argument 1 to "get_context" of "ConjunctiveGraph" has incompatible type "Node"; expected "Union[IdentifiedNode, str, None]"
  319. subgraph = dataset.get_context(subj) # type: ignore[arg-type]
  320. else:
  321. subgraph = graph
  322. for onode in obj_nodes:
  323. self._add_to_graph(dataset, subgraph, context, onode)
  324. return
  325. if SET in (key, term_id):
  326. for onode in obj_nodes:
  327. self._add_to_graph(dataset, graph, context, onode)
  328. return
  329. if INCLUDED in (key, term_id):
  330. for onode in obj_nodes:
  331. self._add_to_graph(dataset, graph, context, onode)
  332. return
  333. if context.version >= 1.1 and key in context.get_keys(NEST):
  334. term = context.terms.get(key)
  335. if term and term.id is None:
  336. return
  337. objs = obj if isinstance(obj, list) else [obj]
  338. for obj in objs:
  339. if not isinstance(obj, dict):
  340. continue
  341. for nkey, nobj in obj.items():
  342. # NOTE: we've already captured subject
  343. if nkey in context.get_keys(ID):
  344. continue
  345. subcontext = context.get_context_for_type(obj)
  346. # type error: Argument 3 to "_key_to_graph" of "Parser" has incompatible type "Optional[Context]"; expected "Context"
  347. self._key_to_graph(dataset, graph, subcontext, subj, nkey, nobj) # type: ignore[arg-type]
  348. return
  349. pred_uri = term.id if term else context.expand(key)
  350. context = context.get_context_for_term(term)
  351. # Flatten deep nested lists
  352. def flatten(n: Iterable[Any]) -> List[Any]:
  353. flattened = []
  354. for obj in n:
  355. if isinstance(obj, dict):
  356. objs = context.get_set(obj)
  357. if objs is not None:
  358. obj = objs
  359. if isinstance(obj, list):
  360. flattened += flatten(obj)
  361. continue
  362. flattened.append(obj)
  363. return flattened
  364. obj_nodes = flatten(obj_nodes)
  365. if not pred_uri:
  366. return
  367. if term and term.reverse:
  368. reverse = not reverse
  369. pred: IdentifiedNode
  370. bid = self._get_bnodeid(pred_uri)
  371. if bid:
  372. if not self.generalized_rdf:
  373. return
  374. pred = BNode(bid)
  375. if self.skolemize:
  376. pred = pred.skolemize()
  377. else:
  378. pred = URIRef(pred_uri)
  379. for obj_node in obj_nodes:
  380. obj = self._to_object(dataset, graph, context, term, obj_node)
  381. if obj is None:
  382. continue
  383. if reverse:
  384. graph.add((obj, pred, subj))
  385. else:
  386. graph.add((subj, pred, obj))
  387. def _parse_container(
  388. self, context: Context, term: Term, obj: Dict[str, Any]
  389. ) -> List[Any]:
  390. if LANG in term.container:
  391. obj_nodes = []
  392. for lang, values in obj.items():
  393. if not isinstance(values, list):
  394. values = [values]
  395. if lang in context.get_keys(NONE):
  396. obj_nodes += values
  397. else:
  398. for v in values:
  399. obj_nodes.append((v, lang))
  400. return obj_nodes
  401. v11 = context.version >= 1.1
  402. if v11 and GRAPH in term.container and ID in term.container:
  403. return [
  404. (
  405. dict({GRAPH: o})
  406. if k in context.get_keys(NONE)
  407. else dict({ID: k, GRAPH: o}) if isinstance(o, dict) else o
  408. )
  409. for k, o in obj.items()
  410. ]
  411. elif v11 and GRAPH in term.container and INDEX in term.container:
  412. return [dict({GRAPH: o}) for k, o in obj.items()]
  413. elif v11 and GRAPH in term.container:
  414. return [dict({GRAPH: obj})]
  415. elif v11 and ID in term.container:
  416. return [
  417. (
  418. dict({ID: k}, **o)
  419. if isinstance(o, dict) and k not in context.get_keys(NONE)
  420. else o
  421. )
  422. for k, o in obj.items()
  423. ]
  424. elif v11 and TYPE in term.container:
  425. return [
  426. (
  427. self._add_type(
  428. context,
  429. (
  430. {ID: context.expand(o) if term.type == VOCAB else o}
  431. if isinstance(o, str)
  432. else o
  433. ),
  434. k,
  435. )
  436. if isinstance(o, (dict, str)) and k not in context.get_keys(NONE)
  437. else o
  438. )
  439. for k, o in obj.items()
  440. ]
  441. elif INDEX in term.container:
  442. obj_nodes = []
  443. for key, nodes in obj.items():
  444. if not isinstance(nodes, list):
  445. nodes = [nodes]
  446. for node in nodes:
  447. if v11 and term.index and key not in context.get_keys(NONE):
  448. if not isinstance(node, dict):
  449. node = {ID: node}
  450. values = node.get(term.index, [])
  451. if not isinstance(values, list):
  452. values = [values]
  453. values.append(key)
  454. node[term.index] = values
  455. obj_nodes.append(node)
  456. return obj_nodes
  457. return [obj]
  458. @staticmethod
  459. def _add_type(context: Context, o: Dict[str, Any], k: str) -> Dict[str, Any]:
  460. otype = context.get_type(o) or []
  461. if otype and not isinstance(otype, list):
  462. otype = [otype]
  463. otype.append(k)
  464. o[TYPE] = otype
  465. return o
  466. def _to_object(
  467. self,
  468. dataset: Graph,
  469. graph: Graph,
  470. context: Context,
  471. term: Optional[Term],
  472. node: Any,
  473. inlist: bool = False,
  474. ) -> Optional[Node]:
  475. if isinstance(node, tuple):
  476. value, lang = node
  477. if value is None:
  478. # type error: Return value expected
  479. return # type: ignore[return-value]
  480. if lang and " " in lang:
  481. # type error: Return value expected
  482. return # type: ignore[return-value]
  483. return Literal(value, lang=lang)
  484. if isinstance(node, dict):
  485. node_list = context.get_list(node)
  486. if node_list is not None:
  487. if inlist and not self.allow_lists_of_lists:
  488. # type error: Return value expected
  489. return # type: ignore[return-value]
  490. listref = self._add_list(dataset, graph, context, term, node_list)
  491. if listref:
  492. return listref
  493. else: # expand compacted value
  494. if term and term.type:
  495. if term.type == JSON:
  496. node = self._to_typed_json_value(node)
  497. elif node is None:
  498. # type error: Return value expected
  499. return # type: ignore[return-value]
  500. elif term.type == ID and isinstance(node, str):
  501. node = {ID: context.resolve(node)}
  502. elif term.type == VOCAB and isinstance(node, str):
  503. node = {ID: context.expand(node) or context.resolve_iri(node)}
  504. else:
  505. node = {TYPE: term.type, VALUE: node}
  506. else:
  507. if node is None:
  508. # type error: Return value expected
  509. return # type: ignore[return-value]
  510. if isinstance(node, float):
  511. return Literal(node, datatype=XSD.double)
  512. if term and term.language is not UNDEF:
  513. lang = term.language
  514. else:
  515. lang = context.language
  516. return Literal(node, lang=lang)
  517. lang = context.get_language(node)
  518. datatype = not lang and context.get_type(node) or None
  519. value = context.get_value(node)
  520. # type error: Unsupported operand types for in ("Optional[Any]" and "Generator[str, None, None]")
  521. if datatype in context.get_keys(JSON): # type: ignore[operator]
  522. node = self._to_typed_json_value(value)
  523. datatype = context.get_type(node)
  524. value = context.get_value(node)
  525. if lang or context.get_key(VALUE) in node or VALUE in node:
  526. if value is None:
  527. return None
  528. if lang:
  529. if " " in lang:
  530. # type error: Return value expected
  531. return # type: ignore[return-value]
  532. return Literal(value, lang=lang)
  533. elif datatype:
  534. return Literal(value, datatype=context.expand(datatype))
  535. else:
  536. return Literal(value)
  537. else:
  538. return self._add_to_graph(dataset, graph, context, node)
  539. def _to_rdf_id(self, context: Context, id_val: str) -> Optional[IdentifiedNode]:
  540. bid = self._get_bnodeid(id_val)
  541. if bid:
  542. b = BNode(bid)
  543. if self.skolemize:
  544. return b.skolemize()
  545. return b
  546. else:
  547. uri = context.resolve(id_val)
  548. if not self.generalized_rdf and ":" not in uri:
  549. return None
  550. node: IdentifiedNode = URIRef(uri)
  551. if not str(node):
  552. if id_val not in self.invalid_uri_to_bnode:
  553. self.invalid_uri_to_bnode[id_val] = BNode(secrets.token_urlsafe(20))
  554. node = self.invalid_uri_to_bnode[id_val]
  555. return node
  556. def _get_bnodeid(self, ref: str) -> Optional[str]:
  557. if not ref.startswith("_:"):
  558. # type error: Return value expected
  559. return # type: ignore[return-value]
  560. bid = ref.split("_:", 1)[-1]
  561. return bid or None
  562. def _add_list(
  563. self,
  564. dataset: Graph,
  565. graph: Graph,
  566. context: Context,
  567. term: Optional[Term],
  568. node_list: Any,
  569. ) -> IdentifiedNode:
  570. if not isinstance(node_list, list):
  571. node_list = [node_list]
  572. first_subj: Union[URIRef, BNode] = BNode()
  573. if self.skolemize and isinstance(first_subj, BNode):
  574. first_subj = first_subj.skolemize()
  575. rest: Union[URIRef, BNode, None]
  576. subj, rest = first_subj, None
  577. for node in node_list:
  578. if node is None:
  579. continue
  580. if rest:
  581. # type error: Statement is unreachable
  582. graph.add((subj, RDF.rest, rest)) # type: ignore[unreachable]
  583. subj = rest
  584. obj = self._to_object(dataset, graph, context, term, node, inlist=True)
  585. if obj is None:
  586. continue
  587. graph.add((subj, RDF.first, obj))
  588. rest = BNode()
  589. if self.skolemize and isinstance(rest, BNode):
  590. rest = rest.skolemize()
  591. if rest:
  592. graph.add((subj, RDF.rest, RDF.nil))
  593. return first_subj
  594. else:
  595. return RDF.nil
  596. @staticmethod
  597. def _to_typed_json_value(value: Any) -> Dict[str, str]:
  598. if _HAS_ORJSON:
  599. val_string: str = orjson.dumps(
  600. value,
  601. option=orjson.OPT_SORT_KEYS | orjson.OPT_NON_STR_KEYS,
  602. ).decode("utf-8")
  603. else:
  604. val_string = json.dumps(
  605. value, separators=(",", ":"), sort_keys=True, ensure_ascii=False
  606. )
  607. return {
  608. TYPE: RDF.JSON,
  609. VALUE: val_string,
  610. }
  611. @classmethod
  612. def _expand_nested_list(cls, obj_nodes: List[Any]) -> Dict[str, List[Any]]:
  613. result = [
  614. cls._expand_nested_list(o) if isinstance(o, list) else o for o in obj_nodes
  615. ]
  616. return {LIST: result}