| # Copyright 2019 The Fuchsia Authors. All rights reserved. |
| # Use of this source code is governed by a BSD-style license that can be |
| # found in the LICENSE file. |
| |
| import re |
| |
| from recipe_engine import recipe_api |
| |
| |
| class JsonUtilApi(recipe_api.RecipeApi): |
| """JsonUtilApi contains JSON-related utilities.""" |
| |
| def extract_from_text(self, name, text, key, default_contents): |
| """Extracts JSON from supplied text. |
| |
| It is expected that the JSON substring appears in the text as |
| <key>:`<JSON>`. |
| |
| Args: |
| name (str): The name of the step. |
| text (str): Text containing a JSON substring. |
| key (str): A key in the text to match against. |
| default_contents (obj): A JSON-serializable Python object to return |
| in the event that no JSON substring is found. |
| |
| Returns: |
| A JSON object representing the extracted JSON string from the text. |
| """ |
| with self.m.step.nest(name): |
| regex = r'^\s*%s:[\s\n]*`((.|\n)*?)`' % key |
| match = re.search(regex, text, re.MULTILINE) |
| result = str(default_contents) |
| if match: |
| result = match.group(1) |
| self.m.step.active_result.presentation.logs['value'] = result.splitlines() |
| try: |
| return self.m.json.loads(result) |
| except ValueError as e: |
| raise self.m.step.StepFailure('failed to load JSON: %s' % str(e)) |