blob: 4dd838c0a559941ac6ee290dfb2faea54dd1ae00 [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
Harald Weltec91085e2022-02-10 18:05:45 +010028
Harald Welte0d4e98a2021-04-07 00:14:40 +020029def js_path_find(js_dict, js_path):
30 """Find/Match a JSON path within a given JSON-serializable dict.
31 Args:
32 js_dict : JSON-serializable dict to operate on
33 js_path : JSONpath string
34 Returns: Result of the JSONpath expression
35 """
36 jsonpath_expr = jsonpath_ng.parse(js_path)
37 return jsonpath_expr.find(js_dict)
38
Harald Weltec91085e2022-02-10 18:05:45 +010039
Harald Welte0d4e98a2021-04-07 00:14:40 +020040def js_path_modify(js_dict, js_path, new_val):
41 """Find/Match a JSON path within a given JSON-serializable dict.
42 Args:
43 js_dict : JSON-serializable dict to operate on
44 js_path : JSONpath string
45 new_val : New value for field in js_dict at js_path
46 """
47 jsonpath_expr = jsonpath_ng.parse(js_path)
48 jsonpath_expr.find(js_dict)
49 jsonpath_expr.update(js_dict, new_val)