Commit 60471c5c authored by Mikaël Salson's avatar Mikaël Salson Committed by Vidjil Team

vidjil_utils: Search and traverse a JSON file

parent 1ced3f8f
import math
import re
import defs
import json
from gluon import current
from datetime import date
......@@ -136,6 +137,53 @@ def search_first_regex_in_file(regex, filename, max_nb_line=None):
return matched_keys
#### Utilities on JSON
def extract_value_from_json_path(json_path, json):
Highly inspired from
Takes a path (for instance field1/field2/field3) and returns
the value at that path.
If the value doesn't exist None will be returned.
elem = json
for x in json_path.strip("/").split("/"):
elem = elem.get(x)
return elem
def extract_fields_from_json(json_fields, pos_in_list, filename):
Takes a map of JSON fields (the key is a common name
and the value is a path) and return a similar map
where the values are the values from the JSON filename.
If the value retrieved from a JSON is an array, we will
get only the item at position <pos_in_list>
json_dict = json.loads(open(filename).read())
except IOError:
json_dict = {}
matched_keys = {}
for field in json_fields:
value = extract_value_from_json_path(json_fields[field], json_dict)
if not isinstance(value, basestring):
matched_keys[field] = value[pos_in_list]
matched_keys[field] = value
return matched_keys
log_patient = re.compile('\((\d+)\)')
log_config = re.compile(' c(\d+)')
log_task = re.compile('\[(\d+)\]')
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment