Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add raw json output to JsonLdExtractor #103

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
22 changes: 10 additions & 12 deletions extruct/jsonld.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,24 @@
class JsonLdExtractor(object):
_xp_jsonld = lxml.etree.XPath('descendant-or-self::script[@type="application/ld+json"]')

def extract(self, htmlstring, base_url=None, encoding="UTF-8"):
def extract(self, htmlstring, base_url=None, encoding="UTF-8", as_json=False):
Gallaecio marked this conversation as resolved.
Show resolved Hide resolved
tree = parse_html(htmlstring, encoding=encoding)
return self.extract_items(tree, base_url=base_url)
return self.extract_items(tree, base_url=base_url, as_json=as_json)

def extract_items(self, document, base_url=None):
def extract_items(self, document, base_url=None, as_json=False):
return [
item
for items in map(self._extract_items, self._xp_jsonld(document))
for items in map(self._extract_items_raw if as_json else self._extract_items, self._xp_jsonld(document))
if items for item in items if item
]

def _extract_items_raw(self, node):
return HTML_OR_JS_COMMENTLINE.sub('', node.xpath('string()'))

def _extract_items(self, node):
script = node.xpath('string()')
try:
# TODO: `strict=False` can be configurable if needed
Granitosaurus marked this conversation as resolved.
Show resolved Hide resolved
data = json.loads(script, strict=False)
except ValueError:
# sometimes JSON-decoding errors are due to leading HTML or JavaScript comments
Granitosaurus marked this conversation as resolved.
Show resolved Hide resolved
data = json.loads(
HTML_OR_JS_COMMENTLINE.sub('', script), strict=False)
script = self._extract_items_raw(node)
# TODO: `strict=False` can be configurable if needed
data = json.loads(script, strict=False)
Gallaecio marked this conversation as resolved.
Show resolved Hide resolved
if isinstance(data, list):
return data
elif isinstance(data, dict):
Expand Down