Create JSON randomly

Since python allows objects to be in JSON format by using json module, objects generated by randog can also be in JSON format.

>>> import json
>>> import randog.factory

>>> factory = randog.factory.randdict(
...     name=randog.factory.randstr(length=16),
...     age=randog.factory.randint(18, 64),
... )

>>> value = factory.next()
>>> value_json = json.dumps(value)

In this case, for example, we get the following string:

{"name": "Wosar5aJMwhngJ72", "age": 51}

Note

The same can be done for command execution by using --json option.

Decimal e.t.c.

Types such as Decimal cannot be converted to JSON by default, but can be converted to JSON by specifying the default function.

>>> import json
>>> import randog.factory

>>> factory = randog.factory.randdict(
...     id=randog.factory.randint(0, 999_999),
...     price=randog.factory.randdecimal(0, 1000, decimal_len=2),
... )

>>> value = factory.next()
>>> value_json = json.dumps(value, default=str)

In this case, for example, we get the following string:

{"id": 583085, "price": "754.10"}

Factory of JSON string

In the previous examples, the objects generated by the factory were converted to JSON, but it is also possible to create a factory that outputs values in JSON format from the beginning by using post_process.

>>> import json
>>> import randog.factory

>>> factory = randog.factory.randdict(
...     name=randog.factory.randstr(length=16),
...     age=randog.factory.randint(18, 64),
... ).post_process(lambda v: json.dumps(v))

>>> value_json = factory.next()