query_json: Do an xpath-like query with json_content.

This commit is contained in:
debugtalk
2017-06-28 21:25:28 +08:00
parent 4250992ad9
commit 83ca01c0b5
2 changed files with 73 additions and 0 deletions

View File

@@ -159,3 +159,36 @@ def parse_content_with_variables(content, variables_binds):
return value
return content
def query_json(json_content, query, delimiter='.'):
""" Do an xpath-like query with json_content.
@param (json_content) json_content
json_content = {
"ids": [1, 2, 3, 4],
"person": {
"name": {
"first_name": "Leo",
"last_name": "Lee",
},
"age": 29,
"cities": ["Guangzhou", "Shenzhen"]
}
}
@param (str) query
"person.name.first_name" => "Leo"
"person.cities.0" => "Guangzhou"
@return queried result
"""
stripped_query = query.strip(delimiter)
if not stripped_query:
return None
try:
for key in stripped_query.split(delimiter):
if isinstance(json_content, list):
key = int(key)
json_content = json_content[key]
except (KeyError, ValueError, IndexError):
raise ParamsError("invalid query string in extract_binds!")
return json_content

View File

@@ -139,3 +139,43 @@ class TestUtils(ApiServerUnittest):
}
with self.assertRaises(exception.ParamsError):
utils.parse_content_with_variables(content, variables_binds)
def test_query_json(self):
json_content = {
"ids": [1, 2, 3, 4],
"person": {
"name": {
"first_name": "Leo",
"last_name": "Lee",
},
"age": 29,
"cities": ["Guangzhou", "Shenzhen"]
}
}
query = "ids.2"
result = utils.query_json(json_content, query)
self.assertEqual(result, 3)
query = "ids.str_key"
with self.assertRaises(exception.ParamsError):
utils.query_json(json_content, query)
query = "ids.5"
with self.assertRaises(exception.ParamsError):
utils.query_json(json_content, query)
query = "person.age"
result = utils.query_json(json_content, query)
self.assertEqual(result, 29)
query = "person.not_exist_key"
with self.assertRaises(exception.ParamsError):
utils.query_json(json_content, query)
query = "person.cities.0"
result = utils.query_json(json_content, query)
self.assertEqual(result, "Guangzhou")
query = "person.name.first_name"
result = utils.query_json(json_content, query)
self.assertEqual(result, "Leo")