Skip to content

Commit

Permalink
mknum
Browse files Browse the repository at this point in the history
  • Loading branch information
amyasnikov committed Mar 6, 2024
1 parent bbfcf0a commit 57dff0b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
8 changes: 4 additions & 4 deletions docs/entities/serializers.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,23 +165,23 @@ For `<a><b>one</b></a>` XML the result will be `{"a": {"b": "one"}}` instead of<

These issues can be handled with **JQ Expression** field. Validity introduces two custom JQ functions:
* **mkarr(path)** wraps expression at *path* into a list if it's not already a list.
* **mknum(path)** tries to convert string at *path* to an integer or a float number.
* **mknum** or **mknum(path)** tries to convert all number-like strings *at path or lower* to numbers. Unlike **mkarr()**, this functions works recursively. So, `. | mknum` which is equivalent of `. | mknum(.)` will be applied to the entire document and will try to convert all number-like strings to numbers.

Let's suppose that you got the following result of XML to JSON coverting:
Let's suppose that you got the following result of XML to JSON converting:
```json
{"a": {"b": "one"}, "c": "10.2"}
```
After applying this JQ expression
```plain
. | mkarr(.a.b) | mknum(.c)
. | mkarr(.a.b) | mknum
```
you'll get
```json
{"a": {"b": ["one"]}, "c": 10.2}
```

### YAML
This method is used to work with already-prepared YAML or JSON data (don't forget that JSON is a subset of YAML). It suits well if you poll your devices via REST API or your vendor has its own tools for getting JSON-formatted config (e.g. `| display json` on Junos).
This method is used to work with already-prepared YAML or JSON data (don't forget that JSON is a subset of YAML). It suits well if you poll your devices via REST API or your vendor has its own tools to get JSON-formatted config (e.g. `| display json` on Junos).


## Fields
Expand Down
6 changes: 5 additions & 1 deletion validity/utils/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ def transform(data_item: Json) -> None:
class jq:
_extra_functions = [
# ensures that expression at "pth" is an array
'def mkarr(pth): . | pth as $tgt | . | pth = if $tgt | type != "array" then [$tgt] else $tgt end'
'def mkarr(pth): . | pth as $tgt | . | pth = if $tgt | type != "array" then [$tgt] else $tgt end',
# recursively converts all number-like strings to numbers
'def mknum(pth):. | pth as $tgt | . | pth = '
'($tgt | walk(if type == "string" and test("[+-]?([0-9]*[.])?[0-9]+") then . | tonumber else . end))',
'def mknum: walk(if type == "string" and test("[+-]?([0-9]*[.])?[0-9]+") then . | tonumber else . end)',
]

@classmethod
Expand Down

0 comments on commit 57dff0b

Please sign in to comment.