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
🌐
Faker
faker.readthedocs.io › en › master › providers › faker.providers.misc.html
faker.providers.misc — Faker 40.11.1 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": ...
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
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
JSON Schema Faker combines JSON Schema standard with fake data generators, allowing users to generate fake data that conform to the schema.
exactly what i need(ed 3 years ago)! More on reddit.com
🌐 r/programming
145
1049
December 21, 2016
🌐
PyPI
pypi.org › project › jsondatafaker
jsondatafaker · PyPI
version: 1 config: locale: en_US #faker locale Default:en_US json: first_name: fake.first_name() last_name: fake.last_name() is_alive: fake.pybool() age: fake.random_int(18, 90) dob: fake.date_of_birth() address: street_address: fake.street_address() city: fake.city() state: fake.state_abbr() postal_code: fake.postcode() phone_numbers: - type: "\"home\"" number: fake.phone_number() - type: "\"office\"" number: fake.phone_number() children: - fake.first_name() - fake.first_name() - fake.first_name() spouse: null
      » pip install jsondatafaker
    
Published   Nov 17, 2023
Version   1.0.1
🌐
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.la...
🌐
GitHub
github.com › ghandic › jsf
GitHub - ghandic/jsf: Creates fake JSON files from a JSON schema · GitHub
from jsf import JSF faker = JSF.from_json("demo-schema.json") fake_json = faker.generate() Or run straight from the commandline... pip install jsf[cli] jsf --schema jsf/tests/data/custom.json --instance wow.json · docker run -v $PWD:/data challisa/jsf jsf --schema /data/custom.json --instance /data/example.json
Starred by 193 users
Forked by 39 users
Languages   Python 97.6% | Starlark 1.9%
🌐
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.
🌐
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"

Find elsewhere
🌐
Linux Hint
linuxhint.com › python-faker-generate-dummy-data
How to Use Python Faker to Generate Dummy Data – Linux Hint
#Import Faker from faker import ... ={} #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() ...
🌐
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
🌐
C# Corner
c-sharpcorner.com › article › python-faker-library
Python Faker Library
January 17, 2022 - import json for i in range(3): ... 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 ...
🌐
GitHub
github.com › Allenzzz › JSONFaker
GitHub - Allenzzz/JSONFaker: A provider for the fake-factory python module that generates fake JSON from a JSON schema
import JSONFaker import requests import faker import sys import json fake = faker.Faker() fake.add_provider(JSONFaker.JSONProvider) response = requests.post(sys.argv[1], data=fake.json(json.load(open(sys.argv[2])))) assert(response.status_code ...
Forked by 3 users
Languages   Python 100.0% | Python 100.0%
🌐
GitHub
github.com › necatiarslan › json-datafaker
GitHub - necatiarslan/json-datafaker: a Python package to generate fake JSON data · GitHub
version: 1 config: locale: en_US #faker locale Default:en_US json: first_name: fake.first_name() last_name: fake.last_name() is_alive: fake.pybool() age: fake.random_int(18, 90) dob: fake.date_of_birth() address: street_address: fake.street_address() city: fake.city() state: fake.state_abbr() postal_code: fake.postcode() phone_numbers: - type: "\"home\"" number: fake.phone_number() - type: "\"office\"" number: fake.phone_number() children: - fake.first_name() - fake.first_name() - fake.first_name() spouse: null
Author   necatiarslan
🌐
Medium
medium.com › @Shamimw › generating-fake-data-csv-json-parquet-using-python-db640a369a6a
Generating Fake data (CSV/JSON/Parquet/XML) using Python | by W Shamim | Medium
January 20, 2026 - Each script uses the Faker library and the repository's configuration-driven FakeDataGenerator class (fake_data_generator.py) to produce synthetic datasets. See the individual script files for usage examples and command-line invocation. ... Run an example: python generate_fake_csv.py python generate_fake_json.py python generate_fake_parquet.py python generate_fake_xml.py python generate_fake_yaml.py python generate_fake_excel.py python generate_fake_tsv.py
🌐
Christophe Avonture
avonture.be › blog › json-faker
JSON - Faker & Mockup | Christophe Avonture
November 19, 2024 - So the idea is to generate a dictionary (a json file) with fake data. Using the Faker library, it's really, really easy. First install the library using pip install faker. And below a small Python script to generate fake data in French (just ...
🌐
DEV Community
dev.to › ghandic › jsf-faking-json-data-from-a-schema-5bj0
jsf - Faking JSON data from a schema - DEV Community
May 4, 2021 - from jsf import JSF faker = JSF.from_json("demo-schema.json") fake_json = faker.generate() Or run stright from the commandline... jsf --schema src/tests/data/custom.json --instance wow.json · docker run -v $PWD:/data challisa/jsf jsf --schema /data/custom.json --instance /data/example.json
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."
🌐
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.
🌐
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.
🌐
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 ...
🌐
Pythonrepo
pythonrepo.com › repo › ghandic-jsf-python-josn
Creates fake JSON files from a JSON schema | PythonRepo
January 4, 2022 - This repository is a Python port of json-schema-faker with some minor differences in implementation.