如何使用python每次生成随机json数据?

问题描述 投票:0回答:2

以下代码生成随机 json 数据:

import json 
my_dict = {'foo': 42, 'bar': {'baz': "Hello", 'poo': 124.2}}
    my_json = json.dumps(my_dict)
    print(my_json)

如何自动化它,以便每次都生成随机的 json 数据。知道 python 中的 faker 库确实会生成随机数据。如何与json结合。

python json python-3.x faker json-schema-faker
2个回答
8
投票
import json 
from faker import Faker
import random
from random import randint
fake = Faker('en_US')
for _ in range(10):
    my_dict = {    'foo': randint(0, 100),    'bar': {'baz': fake.name(),       'poo': float(random.randrange(155, 389))/100   } }
    print(my_dict)

输出:

{'foo': 19, 'bar': {'baz': 'Kimberly Robinson', 'poo': 3.33}}
{'foo': 64, 'bar': {'baz': 'Brandon Goodwin', 'poo': 3.55}}
{'foo': 48, 'bar': {'baz': 'David Jacobs', 'poo': 1.74}}
{'foo': 20, 'bar': {'baz': 'John Stout', 'poo': 2.43}}
{'foo': 68, 'bar': {'baz': 'Janet Adams', 'poo': 2.48}}
{'foo': 57, 'bar': {'baz': 'Amy Odonnell', 'poo': 3.34}}
{'foo': 49, 'bar': {'baz': 'Steven Greene', 'poo': 2.34}}
{'foo': 7, 'bar': {'baz': 'Stephen Robinson', 'poo': 1.93}}
{'foo': 32, 'bar': {'baz': 'Joel Wise', 'poo': 3.37}}
{'foo': 33, 'bar': {'baz': 'Stephanie Thompson DDS', 'poo': 2.41}}

0
投票

您应该将 Python faker 与

python
提供商一起使用

from faker import Faker
from faker.providers import python


faker_instance = Faker()
faker_instance.add_provider(python)

for _ in range(10): print(faker_instance.pydict())

输出

{'difference': 'XtKhOOWEnMEVwdBQTZKK', 'near': 'SxSEiAhlNllUIOYEAOgP', 'traditional': 'dJtBNkBhnFaWHwLrHBHt', 'smile': 'ekuZVVtzILGRoKCIhwig', 'girl': 'ZsjQmrmCodftJCYckbLU', 'should': 2874, 'large': 'MEmwzLYpcImBUMMDiOvq'}
{'help': Decimal('-816553921262963714190480207188163397761028937303864779696321913387013079176148998250529560662726.803676935613970369912423521979839'), 'avoid': '[email protected]', 'the': 'https://www.garcia-kirby.com/list/explore/tags/category.htm', 'street': Decimal('92359.82587426861887700242356498603799947770672114750974269544'), 'democratic': 'FmOoBSVpnYJKQQVRRNqa', 'eye': datetime.datetime(2020, 3, 16, 19, 54, 7), 'nearly': 'jcHDMNxLGdyPYbJVDgMx', 'of': 'iGnlDsKueUUXPxplsfjr', 'catch': Decimal('5808429941673042822540125290455558.40284776629402907172298604656801030417292111988'), 'who': datetime.datetime(2023, 12, 31, 20, 55, 12), 'begin': 'https://www.nelson.org/homepage/'}
{'since': 'http://www.warner.net/', 'support': 8455, 'generation': -37.7537930629464, 'field': Decimal('-88252501212630312827845748370444025388682526179758825415490.819305500553097992977135071609264292181898784157152780726293059256555743276519807635178291640396'), 'adult': 9057, 'sit': 'aFHPgKyCnzaImNuWVJWm'}
{'interview': 'RsCkpXcbCgbwLJhVHZow', 'anything': 2715, 'begin': 'http://owens.com/tags/login.html', 'friend': 'https://www.golden.com/category/', 'particularly': 'opsqxxPFLKvWfpuGzvTf', 'concern': '[email protected]'}
{'very': 'SiFpyiEUIvydplzSsdnK', 'call': '[email protected]', 'wait': datetime.datetime(1977, 5, 12, 23, 14, 2), 'billion': 'gblyONRXNuwrYtQJPyov', 'research': 'zqBGcMzsBslFdsNFobXT', 'special': 'gfxuXtnweLsSLTsjaCoQ', 'join': 'http://www.pacheco-stephens.net/login.php', 'space': 'htpGduxOVXwiCNBXJhPV', 'former': 'rvJIhJIHzZecVkTaHwLs'}
{'success': Decimal('-82125222336.5538894416659852781600699626053200079398781694014863954118508660451107580581336498493078784662195'), 'work': 'FQczLNbaoUsECXYDOSpB', 'still': 4833, 'necessary': 4782, 'mean': 'lGasSjVeucTmxCJUXmWz', 'brother': datetime.datetime(1991, 4, 8, 14, 24, 18), 'market': 'bPOVRFGPHHjQLfEHyJcO', 'save': 'qswmSYPrWLalmPyuPqCa', 'half': '[email protected]'}
{'behavior': 6427, 'middle': Decimal('-41247417180213.000675956930872199214571809016712553850974951669727'), 'Mr': datetime.datetime(2018, 6, 24, 17, 37, 53), 'exist': 8538, 'would': 'https://www.gonzalez.com/home.htm', 'war': 1025}
{'seat': 'BfMuSyhKYOuUflKwzCgG', 'paper': 'http://www.davis.org/', 'standard': 'GSvbGpmKFBCKgVGJHWbj', 'top': 6539, 'recently': 'DaVXXdgzQJfQyXxvFcsS', 'figure': 'PnYaiGglScFLbvNLAaCi', 'tree': 1172, 'yard': 'http://pierce-richards.biz/', 'rich': 'xxXMrnRVCblQVXjlyuPY', 'soon': 57.771010062022, 'difference': datetime.datetime(2016, 10, 21, 1, 27, 55), 'civil': datetime.datetime(2018, 8, 6, 21, 19, 14)}
{'couple': 'fbOpGnxcKByBuFGHEVLo', 'behind': datetime.datetime(2017, 6, 19, 12, 7, 2), 'president': 'zJEzIzWfdNAomqSsTzIi', 'discuss': 9274, 'account': 2596154332.20885, 'but': 'WxrhCGhBefJzvEkOhpVO', 'fall': datetime.datetime(2015, 7, 24, 3, 58, 32)}
{'sure': datetime.datetime(1990, 1, 4, 18, 23, 46), 'building': 'qGqYjAiVeejzrhIlQlZd', 'owner': 'QQRltHuIOnyZXXezjxzY', 'music': 'IMLJLDeLAeQQqGSJcmyD', 'modern': '[email protected]', 'easy': -23176270116.5519, 'outside': Decimal('-3832750279905654828719938006116910474702411801.601731899264109'), 'benefit': 2711}

如果您需要 JSON 可序列化

因为将使用一些 Python 对象,所以您需要使用带有 json.dumps 的自定义类。

示例:

import json
import decimal
from datetime import datetime

from faker import Faker
from faker.providers import python


faker_instance = Faker()
faker_instance.add_provider(python)


class Encoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, datetime):
            return o.isoformat()
        return super().default(o)

for _ in range(10): print(json.dumps(faker_instance.pydict(), cls=Encoder))


输出:

{"piece": -11.2715421845995, "board": "TdZUqkdStQfNtCqkWJSS", "pass": "SLnjqTDsQmnvUkWrwPAR", "toward": "essScwVHrkSHEnipnGSD", "talk": "-398284916306644001591114695871164686817296756270028778947043755.95552398375", "door": "dtYDCUwbpqRGOEReyiTj", "operation": "[email protected]"}
{"area": "GsCoSZIIEXnivDzxwyjy", "town": "40584212140902203.19227823007552307132379296859249538251572412213018525737596538026752952", "reduce": "ytJYNsQKXGsbTbSjRNEU", "way": "SNYEmpcdryrHQtoTwwvw", "what": "lpliykfoYgbXVjKxQXcE", "until": "prMGjmcTyFZIHWmkJqzy", "film": -33521.7157001307, "trip": "wVSRsmOCZsrslLQdmjYi"}
{"read": 7449622054084.3, "look": "uNIGAhLePWUdtXzRjKFd", "set": "JJmIiCNLBOyuYzufganN", "five": -14738887825268.1, "hope": "TDPlDXatWgjOzecmtRYd", "guess": "[email protected]", "style": 4524, "drug": "101660101538120401195146738841103081373.71909390616610582939307490748581547684256709304334403925033466073879311541649035"}
{"civil": "[email protected]", "partner": "https://www.santiago-holden.biz/faq/", "home": "[email protected]", "floor": "gubNwcGfBNACyGsuYjaD", "kind": 1309, "specific": "WSGIUkOrgFwJwbPLAvqL", "character": "1995-08-11T05:36:23", "expect": 4983, "attack": 8321, "grow": "YYwsTTDmQmONXsximdoL"}
{"bad": 1526, "bar": "422273063107390483998344302020772702930338961733965648015840597579283556899010845472815894287.133561389787974813379832863357085842754610382671480291189502137453409374038376391469481092", "church": "oNwSXkaIxLzFHcYlSYfb", "example": -403.18785992753, "hair": "https://garcia.com/", "last": "krcUHtnfxaiZFNtLwafb"}
{"should": "vvHujYVgPGFcShLDcfaw", "save": "bSIVekePyeGVDzxWshui", "measure": "http://graves-rodriguez.com/homepage/", "push": 628, "newspaper": "[email protected]", "structure": "weGKdMiljfmMxetuvAZH", "local": "eHggivQtmpxwyrhBoGOU", "own": "UZXiFYJqbGbttXspfVPq", "provide": -11784001365.8804, "born": "WOzefzElyvTQRYdbleuR", "rather": 2048, "sense": "[email protected]", "action": "fpvsqzrHnsPhYctSFVWu"}
{"difference": "https://www.mills-farmer.com/category/", "amount": "1995-05-24T00:49:19", "site": -2852575.55361594, "industry": "dTwpRSclPiUfqLRglcZU", "line": 81383682342068.1, "near": 1067}
{"race": "1980-09-28T15:10:50", "ever": "TpXNgRucpjyZPmzLypmO", "campaign": 9847, "trade": 2774, "possible": -662401443.325286, "television": "-9922823.335790671886202545", "worker": "http://www.mclaughlin-vazquez.com/search/tags/explore/about.htm", "other": "RRGZDYEHVxTRgBtIoohX", "least": "dWMbUtPdOFjljyvgNukr"}
{"heart": "mwkphqCDuqKCpDMegnvL", "air": "2022-11-21T05:56:51", "money": 5561, "possible": "shZWfrSIoOwovMUBKlYC", "defense": "1978-11-13T00:43:16", "course": 9666, "bill": 7666, "tough": "ZrexVrgGefuOlpgcgckz"}
{"officer": "CQjnNGefluKTxsQwgUqx", "under": "2014-04-12T15:09:50", "per": "wWQgjCrExCOTtlKCVlbL", "bed": "pcPMfNCXWuhLetEMkQbE", "happy": 2255, "continue": 4297, "compare": "cCsjKndPGOkLgEHdTBbu", "first": "2020-07-11T00:59:29", "possible": 6605, "story": -558699294483.201, "whom": "hLjqzsLXtaOpTVYVYUPn", "seek": "XqRUolclcMJGFNVkUorP"}

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.