If I understand correctly, the problem is that you want to generate different data every time. To do that, you need to:

  • Currently the LoginData attributes are generated when the class is defined. If you want them to be different for each instance, make them instance attributes and set them in the __init__() method.

  • You need to create a new LoginData instance in every iteration of the for loop in input_data().

Code:

from faker import Faker
import random


class LoginData:

    def __init__(self):
        fake = Faker()
        self.password = "password@123"
        self.email = fake.email()
        self.username = fake.first_name()
        self.first_name = fake.first_name()
        self.last_name = fake.last_name()
        self.phone = random.randint(9000000000, 9999999999)
        self.city = fake.city()
        self.about = "This is a sample text : about"

    def get_json(self):
        p = {
            'password': self.password,
            'email': self.email,
            'username': self.first_name,
            'first_name': self.first_name,
            'last_name': self.last_name,
            'phone': self.phone,
            'city': self.city,
            'about': self.about
        }
        return p



def input_data(x):
    for i in range(0, x):
        logindata = LoginData()
        print(logindata.get_json())


def main():
    no_of_input = 5
    input_data(no_of_input)


main()

Note that get_json() still returns a Python dict, not JSON. For JSON, you can use the json module in the standard library:

import json

and in get_json()

return json.dumps(p)
Answer from Maximouse on Stack Overflow
🌐
PyPI
pypi.org › project › jsondatafaker
jsondatafaker · PyPI
jsondatafaker is a versatile Python package that empowers you to effortlessly create realistic but synthetic json data for a wide range of applications. If you need to generate test data for software development, this tool simplifies the process ...
      » pip install jsondatafaker
    
Published   Nov 17, 2023
Version   1.0.1
Discussions

Automatic fake JSON data creation from schema
I'm new to Python. Is this just like "Lorem Ipsum" filler content to make JSON's with to test software pipelines with? More on reddit.com
🌐 r/Python
10
7
May 4, 2021
python - generating millions of json data - Stack Overflow
I need some dummy data in json format, to use in another project. I'm currently using the Faker package in the code below: from json import dumps from faker import Faker import collections databa... More on stackoverflow.com
🌐 stackoverflow.com
Newest 'json-schema-faker' Questions - Stack Overflow
Stack Overflow | The World’s Largest Online Community for Developers More on stackoverflow.com
🌐 stackoverflow.com
Generate realistic dummy data in CSV and JSON format
Do you see people using this over Faker? https://github.com/joke2k/faker More on reddit.com
🌐 r/Python
14
18
November 28, 2023
🌐
Faker
faker.readthedocs.io › en › master › providers › faker.providers.misc.html
faker.providers.misc — Faker 40.11.0 documentation
Serialized JSON data · Return type: str · Examples: >>> Faker.seed(0) >>> for _ in range(5): ... fake.json(data_columns={'Spec':'@1.0.1', 'ID':'pyint', 'Details':{'Name':'name', 'Address':'address'}}, num_rows=2) ... '[{"Spec": "1.0.1", "ID": 6311, "Details": {"Name": "Jennifer Green", "Address": "7593 Juan Throughway Apt.
🌐
GitHub
github.com › ghandic › jsf
GitHub - ghandic/jsf: Creates fake JSON files from a JSON schema · GitHub
This repository is a Python port of json-schema-faker with some minor differences in implementation.
Starred by 193 users
Forked by 39 users
Languages   Python 97.6% | Starlark 1.9%
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-faker-library
Python Faker Library - GeeksforGeeks
January 9, 2026 - Python · from faker import Faker import json from random import randint fake = Faker() n1 = 5 students = {} for i in range(n1): students[i] = { 'id': randint(1, 10), 'name': fake.name(), 'address': fake.address(), 'latitude': float(fake.latitude()), 'longitude': float(fake.longitude()) } print(json.dumps(students, indent=4)) with open('students.json', 'w') as fp: json.dump(students, fp, indent=4) print(f"JSON file created with {n1} student records.") Output ·
🌐
Reddit
reddit.com › r/python › automatic fake json data creation from schema
r/Python on Reddit: Automatic fake JSON data creation from schema
May 4, 2021 -

https://github.com/ghandic/jsf

Use jsf along with fake data generators to provide consistent and meaningful fake data for your system.

Main Features

  • Provides out of the box data generation from any JSON schema 📦

  • Extendable custom data providers using any lambda functions 🔗

  • Multi level state for dependant data (eg multiple objects sharing value, such as children with same surname) 🤓

  • Inbuilt validation of fake JSON produced ✅

  • In memory conversion from JSON Schema to Pydantic Models with generated examples 🤯

  • Seamless integration with FastAPI 🚀

Installation

$ pip install jsf

---> 100%

Usage

Basic 😊

from jsf import JSF

faker = JSF(
    {
        "type": "object",
        "properties": {
            "name": {"type": "string", "$provider": "faker.name"},
            "email": {"type": "string", "$provider": "faker.email"},
        },
        "required": ["name", "email"],
    }
)

fake_json = faker.generate()

Results in ...

{
    'name': 'Jesse Phillips', 
    'email': 'xroberson@hotmail.com'
}

From JSON file 📁

from jsf import JSF

faker = JSF.from_json("demo-schema.json")
fake_json = faker.generate()

<details markdown="1"> <summary>Or run stright from the <code>commandline</code>...</summary>

Native install

jsf --schema src/tests/data/custom.json --instance wow.json

Docker

docker run -v $PWD:/data challisa/jsf jsf --schema /data/custom.json --instance /data/example.json

</details>

FastAPI Integration 🚀

Create a file main.py with:

from jsf import JSF
from fastapi import FastAPI

app = FastAPI(docs_url="/")
generator = JSF.from_json("custom.json")


@app.get("/generate", response_model=generator.pydantic())
def read_root():
    return generator.generate()

Run the server with:

<div class="termy">

$ uvicorn main:app --reload

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [28720]
INFO:     Started server process [28722]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Navigate to http://127.0.0.1:8000 and check out your endpoint. Notice the following are all automatically created:

  • Schema with descriptions and examples

  • Example response

  • Data generation by clicking "try it out"

🌐
Linux Hint
linuxhint.com › python-faker-generate-dummy-data
How to Use Python Faker to Generate Dummy Data – Linux Hint
All customer data will be stored in a dictionary and stored in the customer.json file by using the JSON module. #Import Faker from faker import Faker #Import JSON import json #Declare faker onject fake = Faker() #Define function to generate fake data and store into a JSON file def generate_data(records): #Declare an empty dictionary customer ={} #Iterate the loop based on the input value and generate fake data for n in range(0, records): customer[n]={} customer[n]['id']= fake.random_number(digits=5) customer[n]['name']= fake.name() customer[n]['address']= fake.address() customer[n]['email']= s
Find elsewhere
🌐
PyPI
pypi.org › project › faker-schema
faker-schema
July 16, 2017 - JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Christophe Avonture
avonture.be › blog › json-faker
JSON - Faker & Mockup | Christophe Avonture
November 19, 2024 - Generate and validate JSON data using Python's Faker library and Mockaroo. Learn to create fake data for testing and ensure file quality with schemas.
🌐
Towards Data Science
towardsdatascience.com › home › latest › faker library in python – an intriguing expedient for data scientists
Faker library in python - An intriguing expedient for data scientists | Towards Data Science
March 5, 2025 - The following code snippet generates the details of 2 random employees consisting of their Employee Id, Name, Address, Job, and City and finally generates a separate JSON file that can be consumed anywhere else. #Import libraries from faker import Faker import json from random import randint
🌐
PyPI
pypi.org › project › faker-cli
faker-cli · PyPI
Some Faker providers (like pyint) take arguments. You can also specify those if you like, separated by semi-colons (because some arguments take a comma-separated string :)) fake -n 10 "pyint(1;100),credit_card_number(amex),pystr_format(?#-####)" -f json -c id,credit_card_number,license_plate
      » pip install faker-cli
    
Published   Jul 11, 2024
Version   0.7.0
🌐
GitHub
github.com › necatiarslan › json-datafaker
GitHub - necatiarslan/json-datafaker: a Python package to generate fake JSON data · GitHub
jsondatafaker is a versatile Python package that empowers you to effortlessly create realistic but synthetic json data for a wide range of applications. If you need to generate test data for software development, this tool simplifies the process ...
Author   necatiarslan
🌐
Paul Apivat
paulapivat.com › technical_notes › example_tech › python_faker
Using Faker to simulate fake data with Python | Paul Apivat
Database is set to an empty array which will store the json object (OrderedDict). We’ll save the file that we eventually write as testing_bounty and keep it a short length (5), while we’re still testing. Finally, we initialize the Faker library by calling the Faker function and setting to fake.
🌐
GitHub
github.com › joke2k › faker
GitHub - joke2k/faker: Faker is a Python package that generates fake data for you. · GitHub
Faker is a Python package that generates fake data for you. - joke2k/faker
Starred by 19.2K users
Forked by 2.1K users
Languages   Python
🌐
C# Corner
c-sharpcorner.com › article › python-faker-library
Python Faker Library
January 17, 2022 - import json for i in range(3): employee ={} employee[i]={} employee[i]['name']= fake.name() employee[i]['address']= fake.address() employee[i]['state']= str(fake.state()) employee[i]['country']= str(fake.country()) employee[i]['ssn']= str(fake.ssn()) print(json.dumps(employee, sort_keys=True, indent=4)) Faker library is capable enough of generating locale-specific data, like generating fake Japanese names · fake_jp = Faker('ja_JP') for i in range(10): print(fake_jp.name()) ... We have seen how to work with the Python Faker package for generating various types of data.
🌐
Blue Book
lyz-code.github.io › blue-book › coding › python › faker
Faker - The Blue Book
OptionalProvider uses existent faker providers to create the data, so you can use the provider method arguments. For example, optional_int uses the python provider pyint, so you can use the min_value, max_value, and step arguments.
Top answer
1 of 3
3

You do not need to use OrderedDict: JSON format may not (and will not) save order of items. Even if order will be saved in the file - it will breaks when another project will parse that file.

You just need to use dict. Also it will be much more faster.

To save the order of items you should explicitly preserve the index of an each element. Like this:

from json import dumps
from faker import Faker
import collections
import json

def fake_person_generator(length, fake):
    for x in range(length):  # xrange in Python 2.7
        yield {'last_name': fake.last_name(),
               'first_name': fake.first_name(),
               'street_address': fake.street_address(),
               'email': fake.email(),
               'index': x}

database = []
filename = '1M'
length   = 1000000
fake     = Faker() # <--- Forgot this
fpg = fake_person_generator(length, fake)
with open('%s.json' % filename, 'w') as output:
    output.write('[')  # to made json file valid according to JSON format
    for person in fpg:
        json.dump(person, output)
    output.write(']')  # to made json file valid according to JSON format
print "Done."
2 of 3
1

You go out-of-memory because you first generate the whole database first, and then dump the database. A more memory-friendy way would be to generate the dict entries on the fly. A better way would be to use a generator which makes the entries on the fly.

def fake_person_generator(length):
    for x in range(length):  # xrange in Python 2.7
        yield OrderedDict([
            ('last_name', 'lastname_%i' % x),
            ('first_name', 'firstname_%i' % x),
            ('street_address', 'adress_%i' % x),
            ('email', 'email_%i' % x)])

Combined with Alex Hall's answer this should reduce the memory need dramatically.

I don't know the json-module so well, but the writing would be something like:

length = 1000000
fpg = fake_person_generator(length)
with open('%s.json' % filename, 'w') as output:
    for person in fpg:
        json.dump(person, output)
print "Done."
🌐
Mimesis
mimesis.name
Mimesis: Fake Data Generator — Mimesis 19.0.0 documentation
Mimesis is a high-performance fake data generator for Python, which provides data for a variety of purposes in a variety of languages. The fake data could be used to populate a testing database, create fake API endpoints, create JSON and XML files of arbitrary structure, anonymize data taken ...
🌐
Medium
medium.com › @abhr1994 › generate-sample-data-using-faker-cc0c8707cf80
Generate Sample Data using Faker. In this article lets see how we can… | by Abhishek Raviprasad | Medium
December 14, 2022 - Below is the script to generate the fake data needed for quick testing in desired format (CSV/JSON). import csv from faker import Faker import argparse import json from decimal import * from datetime import date, datetime fake = Faker() class CustomEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return str(obj) if isinstance(obj, (datetime, date)): return obj.isoformat() # or return str(obj) return json.JSONEncoder.default(self, obj) def main(): parser = argparse.ArgumentParser(description='Faker') parser.add_argument('--output_format', default="csv", type=str, help='Pass the output format.
🌐
Stack Overflow
stackoverflow.com › questions › tagged › json-schema-faker
Newest 'json-schema-faker' Questions - Stack Overflow
Using the following schema: and a very simple package.json with the only dependency being json-schema-faker (0.5.0.rc16), when I run the following code I see the output shown at the bottom (an ...