Skip to content

Instantly share code, notes, and snippets.

@filinvadim
Created November 9, 2017 15:07
Show Gist options
  • Save filinvadim/064aac84da96639be72481508af5e15e to your computer and use it in GitHub Desktop.
Save filinvadim/064aac84da96639be72481508af5e15e to your computer and use it in GitHub Desktop.
Group Travelport xml
def regroup_response(self):
"""
Groups elements of request by keys and references on keys.
NOTE that those keys and references actually have meaning of primary and foreign key
in the terms of SQL.
:param data: json like request (actually dicts with lists and strings)
:return: None
"""
keys = {}
def _collect_primary_keys(data, keys):
"""
Finds every "Key" attribute in elements which NOT ends with "Ref" word
and collect those keys with view below:
{'AmjuJUjUQHKqzIpQntPbiQ==':{'BookingTraveler': ('@SomeAttr','Somevalue')}}.
Deletes above keys in data.
:param data: json like request (actually dicts with lists and strings)
:param keys: dict
:return: None
"""
if isinstance(data, dict):
for key, value in data.items():
if '#' not in key and '@' not in key and 'Ref' not in key: # ref not in
if isinstance(value, dict):
if value.get("@Key"):
keys[value['@Key']] = {key: value}
del value['@Key']
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
_collect_primary_keys({key: item}, keys)
_collect_primary_keys(value, keys)
elif isinstance(data, list):
for item in data:
_collect_primary_keys(item, keys)
_collect_primary_keys(self._data, keys)
if len(keys) == 0:
return ValueError('No single key was parsed')
def _substitute_refs_with_keys(data, keys):
"""
Finds every "Key" attribute in elements which ENDS with "Ref" word
and REPLACE (by deleting) those elements with matching elements in 'Keys' by very keys.
Deletes parental elements which were inserted instead of refs.
:param data: json like request (actually dicts with lists and strings)
:param keys: dict with keys and elements
:return: None
"""
if isinstance(data, dict):
for tag, value in data.items():
if '@' not in tag and 'Ref' in tag: # ref in
if isinstance(value, dict):
if value.get("@Key"):
for key, element in keys.items():
if value['@Key'] == key:
for k, v in element.items():
data[k] = v
del data[tag]
elif isinstance(value, list):
value_list = []
for item in value:
if item.get("@Key"):
for key, element in keys.items():
if item['@Key'] == key:
for k, v in element.items():
value_list.append(v)
data[k] = value_list
del data[tag]
_substitute_refs_with_keys(value, keys)
elif isinstance(data, list):
for item in data:
_substitute_refs_with_keys(item, keys)
_substitute_refs_with_keys(self._data, keys)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment