blob: 98dbd75de55b9ee9b96162cccc8e7a0fb0bc5c3b [file] [log] [blame]
Harald Welte0d4e98a2021-04-07 00:14:40 +02001# coding=utf-8
2import json
3import pprint
4import jsonpath_ng
5
6"""JSONpath utility functions as needed within pysim.
7
8As pySim-sell has the ability to represent SIM files as JSON strings,
9adding JSONpath allows us to conveniently modify individual sub-fields
10of 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
28def 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
38def 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