Harald Welte | 0d4e98a | 2021-04-07 00:14:40 +0200 | [diff] [blame^] | 1 | # coding=utf-8 |
| 2 | import json |
| 3 | import pprint |
| 4 | import jsonpath_ng |
| 5 | |
| 6 | """JSONpath utility functions as needed within pysim. |
| 7 | |
| 8 | As pySim-sell has the ability to represent SIM files as JSON strings, |
| 9 | adding JSONpath allows us to conveniently modify individual sub-fields |
| 10 | of a file or record in its JSON representation. |
| 11 | """ |
| 12 | |
| 13 | # (C) 2021 by Harald Welte <laforge@osmocom.org> |
| 14 | # |
| 15 | # This program is free software: you can redistribute it and/or modify |
| 16 | # it under the terms of the GNU General Public License as published by |
| 17 | # the Free Software Foundation, either version 2 of the License, or |
| 18 | # (at your option) any later version. |
| 19 | # |
| 20 | # This program is distributed in the hope that it will be useful, |
| 21 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 22 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 23 | # GNU General Public License for more details. |
| 24 | # |
| 25 | # You should have received a copy of the GNU General Public License |
| 26 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 27 | |
| 28 | def js_path_find(js_dict, js_path): |
| 29 | """Find/Match a JSON path within a given JSON-serializable dict. |
| 30 | Args: |
| 31 | js_dict : JSON-serializable dict to operate on |
| 32 | js_path : JSONpath string |
| 33 | Returns: Result of the JSONpath expression |
| 34 | """ |
| 35 | jsonpath_expr = jsonpath_ng.parse(js_path) |
| 36 | return jsonpath_expr.find(js_dict) |
| 37 | |
| 38 | def js_path_modify(js_dict, js_path, new_val): |
| 39 | """Find/Match a JSON path within a given JSON-serializable dict. |
| 40 | Args: |
| 41 | js_dict : JSON-serializable dict to operate on |
| 42 | js_path : JSONpath string |
| 43 | new_val : New value for field in js_dict at js_path |
| 44 | """ |
| 45 | jsonpath_expr = jsonpath_ng.parse(js_path) |
| 46 | jsonpath_expr.find(js_dict) |
| 47 | jsonpath_expr.update(js_dict, new_val) |
| 48 | |