1
+ import os
2
+ from json import JSONDecodeError , loads
3
+
1
4
from deprecated import deprecated
2
5
3
6
from redis .exceptions import DataError
4
7
5
8
from .decoders import decode_dict_keys
6
9
from .path import Path
7
- from json import loads , JSONDecodeError
8
- import os
9
10
10
11
11
12
class JSONCommands :
@@ -217,31 +218,37 @@ def set(self, name, path, obj, nx=False, xx=False, decode_keys=False):
217
218
218
219
def set_file (self , name , path , file_name , nx = False , xx = False , decode_keys = False ):
219
220
"""
220
- Set the JSON value at key ``name`` under the ``path`` to the contents of the json file ``file_name``.
221
+ Set the JSON value at key ``name`` under the ``path`` to the content
222
+ of the json file ``file_name``.
221
223
222
224
``nx`` if set to True, set ``value`` only if it does not exist.
223
225
``xx`` if set to True, set ``value`` only if it exists.
224
226
``decode_keys`` If set to True, the keys of ``obj`` will be decoded
225
227
with utf-8.
226
228
227
229
"""
228
- try :
229
- file_content = loads (file_name )
230
- except JSONDecodeError :
231
- raise JSONDecodeError ("Inappropriate file type, set_file() requires json file" )
232
-
230
+
231
+ with open (file_name , "r" ) as fp :
232
+ file_content = loads (fp .read ())
233
+
233
234
return self .set (name , path , file_content , nx , xx , decode_keys )
234
235
236
+ def set_path (self , json_path , root_folder , nx = False , xx = False , decode_keys = False ):
237
+ """
238
+ Iterate over ``root_folder`` and set each JSON file to a value
239
+ under ``json_path`` with the file name as the key.
235
240
236
- def set_path (self , json_path , root_directory , nx = False , xx = False , decode_keys = False ):
237
- """
241
+ ``nx`` if set to True, set ``value`` only if it does not exist.
242
+ ``xx`` if set to True, set ``value`` only if it exists.
243
+ ``decode_keys`` If set to True, the keys of ``obj`` will be decoded
244
+ with utf-8.
238
245
239
246
"""
240
247
set_files_result = {}
241
- for root , dirs , files in os .walk (root_directory ):
248
+ for root , dirs , files in os .walk (root_folder ):
242
249
for file in files :
243
250
try :
244
- file_name = file .rsplit ('.' )[0 ]
251
+ file_name = os . path . join ( root , file ) .rsplit ("." )[0 ]
245
252
file_path = os .path .join (root , file )
246
253
self .set_file (file_name , json_path , file_path , nx , xx , decode_keys )
247
254
set_files_result [os .path .join (root , file )] = True
@@ -250,8 +257,6 @@ def set_path(self, json_path, root_directory , nx=False, xx=False, decode_keys=F
250
257
251
258
return set_files_result
252
259
253
-
254
-
255
260
def strlen (self , name , path = None ):
256
261
"""Return the length of the string JSON value under ``path`` at key
257
262
``name``.
0 commit comments