Skip to content

Commit

Permalink
Allow simple Python objects to be used as argument to jsonize()
Browse files Browse the repository at this point in the history
  • Loading branch information
tkeffer committed Nov 18, 2024
1 parent 8e3128c commit 1566a76
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
2 changes: 2 additions & 0 deletions docs_src/changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ stations.

Fix bug that prevented relative paths to the config file from working.

Allow simple Python objects to be used as an argument to `$jsonize()`.


### 5.1.0 07/04/2024

Expand Down
9 changes: 6 additions & 3 deletions src/weewx/cheetahgenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -643,13 +643,16 @@ def jsonize(arg):
Format my argument as JSON
Args:
arg (iterable): An iterable, such as a list, or zip structure
arg (iterable|object): Python object, or an iterable
Returns:
str: The argument formatted as JSON.
"""
val = list(arg)
return json.dumps(val, cls=weewx.units.ComplexEncoder)
try:
result = json.dumps(arg, cls=weewx.units.ComplexEncoder)
except TypeError:
result = json.dumps(list(arg), cls=weewx.units.ComplexEncoder)
return result

@staticmethod
def rnd(arg, ndigits):
Expand Down
4 changes: 4 additions & 0 deletions src/weewx/tests/test_cheetah.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ def test_jsonize(self):
'[[0, 1], [null, 3], [4, 5]]')
self.assertEqual(weewx.cheetahgenerator.JSONHelpers.jsonize([complex(1,2), complex(3,4)]),
'[[1.0, 2.0], [3.0, 4.0]]')
self.assertEqual(weewx.cheetahgenerator.JSONHelpers.jsonize([1,2,3]),
'[1, 2, 3]')
self.assertEqual(weewx.cheetahgenerator.JSONHelpers.jsonize({'a': 1, 'b': 2}),
'{"a": 1, "b": 2}')

def test_rnd(self):
self.assertEqual(weewx.cheetahgenerator.JSONHelpers.rnd(1.2345, 2), 1.23)
Expand Down

0 comments on commit 1566a76

Please sign in to comment.