Last active
August 21, 2020 12:48
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"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()}}" | |
} | |
] | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Move to https://github.com/KevCui/Fakergen