Skip to content

Instantly share code, notes, and snippets.

@KevCui
Last active August 21, 2020 12:48
Show Gist options
  • Save KevCui/db5f1e697243a685901b5cf908e23e72 to your computer and use it in GitHub Desktop.
Save KevCui/db5f1e697243a685901b5cf908e23e72 to your computer and use it in GitHub Desktop.
Generate mock json data with a structured template using Faker under the hood
#!/usr/bin/python3
# ~$ ./jsonfaker.py <json_template>
import sys
import re
from faker import Faker
from faker.providers import BaseProvider
class customProvider(BaseProvider):
sentences = (
'Hello world',
'Hi there',
'Ciao Bello',
)
def greeting(self):
return self.random_element(self.sentences)
fake = Faker()
fake.add_provider(customProvider)
jsontemplate = sys.argv[1]
pattern = r'\{\{\w+\([\w=,\s?#\'\":-]*\)\}\}'
with open(jsontemplate) as f:
content = f.read().splitlines()
for line in content:
num = len(re.findall(pattern, line))
if num != 0:
newline = line
for i in range(1, num+1):
item = re.findall(pattern, newline)
newline = newline.replace(item[0], str(eval('fake.' + re.sub(r'[\{\}]', '', item[0]))), 1)
print(newline)
else:
print(line)
[
{
"product_number": "{{bothify(text='????-########', letters='ABCDE')}}",
"hostname": "{{hostname(2)}}",
"attributes": [
{
"ean": "{{ean13(leading_zero=False)}}",
"random_number": "{{pyint(min_value=1, max_value=999, step=1)}}",
"color": "{{color_name()}} {{color_name()}}",
"text": "static text",
"custom_greeting": "{{greeting()}}"
}
]
}
]
@KevCui
Copy link
Author

KevCui commented Aug 1, 2020

Need to repeat a certain part of the template? Using jq and creating a new template will simply do the job, for example:
jq '.[].attributes += $el' --argjson el "$(jq '.[].attributes' template.json)" template.json > newtemplate.json

Need more repeats? for loop it.

@KevCui
Copy link
Author

KevCui commented Aug 1, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment