|
4 | 4 |
|
5 | 5 | from .decoders import decode_dict_keys
|
6 | 6 | from .path import Path
|
| 7 | +from json import loads, JSONDecodeError |
| 8 | +import os |
7 | 9 |
|
8 | 10 |
|
9 | 11 | class JSONCommands:
|
@@ -213,6 +215,43 @@ def set(self, name, path, obj, nx=False, xx=False, decode_keys=False):
|
213 | 215 | pieces.append("XX")
|
214 | 216 | return self.execute_command("JSON.SET", *pieces)
|
215 | 217 |
|
| 218 | + def set_file(self, name, path, file_name, nx=False, xx=False, decode_keys=False): |
| 219 | + """ |
| 220 | + Set the JSON value at key ``name`` under the ``path`` to the contents of the json file ``file_name``. |
| 221 | +
|
| 222 | + ``nx`` if set to True, set ``value`` only if it does not exist. |
| 223 | + ``xx`` if set to True, set ``value`` only if it exists. |
| 224 | + ``decode_keys`` If set to True, the keys of ``obj`` will be decoded |
| 225 | + with utf-8. |
| 226 | +
|
| 227 | + """ |
| 228 | + try: |
| 229 | + file_content = loads(file_name) |
| 230 | + except JSONDecodeError: |
| 231 | + raise JSONDecodeError("Inappropriate file type, set_file() requires json file") |
| 232 | + |
| 233 | + return self.set(name, path, file_content, nx, xx, decode_keys) |
| 234 | + |
| 235 | + |
| 236 | + def set_path(self, json_path, root_directory , nx=False, xx=False, decode_keys=False): |
| 237 | + """ |
| 238 | +
|
| 239 | + """ |
| 240 | + set_files_result = {} |
| 241 | + for root, dirs, files in os.walk(root_directory): |
| 242 | + for file in files: |
| 243 | + try: |
| 244 | + file_name = file.rsplit('.')[0] |
| 245 | + file_path = os.path.join(root, file) |
| 246 | + self.set_file(file_name, json_path, file_path, nx, xx, decode_keys) |
| 247 | + set_files_result[os.path.join(root, file)] = True |
| 248 | + except JSONDecodeError: |
| 249 | + set_files_result[os.path.join(root, file)] = False |
| 250 | + |
| 251 | + return set_files_result |
| 252 | + |
| 253 | + |
| 254 | + |
216 | 255 | def strlen(self, name, path=None):
|
217 | 256 | """Return the length of the string JSON value under ``path`` at key
|
218 | 257 | ``name``.
|
|
0 commit comments