首页 > 解决方案 > 使用 Python 生成随机 Json 数据并存储在变量中

问题描述

我的应用采用这种格式的 JSON。如何使用for循环生成下面提到的格式的数据,并将其存储在变量中?

示例id='123456'

{
    "abo": [

        {
            "id": "1ab",
            "data": fake.text(),
            "place": fake.place(),
            "user_id": id,
        },

        {
            "id": "1ab",
            "data": fake.text(),
            "place": fake.place(),
            "user_id": id,
        }
    ],
    "id": id
}

如何从此格式生成随机数据并将它们存储在给定范围的变量中?

如果范围为 3 ( for i in range(3)),则应转储以下内容。



{
    "abo": [

        {
            "id": "1ab",
            "data": this has been a great day,
            "place": texas,
            "user_id": '123456',
        },
        {
            "id": "1ab",
            "data": Gaurd should be credited,
            "place": newyork,
            "user_id": '123456',
        },
        {
            "id": "1ab",
            "data": fake.text(),
            "place": fake.place(),
            "user_id": '123456',
        }
    ],
    "id": '123456'
}

试过这个,但这不是使用 json 的正确方法:

import json 
from faker import Faker
import random
from random import randint
print('{"abo": [')
fake = Faker('en_US')
for _ in range(20):
       data=
       {
            "id": "1ab",
            "data": fake.text(),
            "place": fake.place(),
            "user_id": id,
        }
    print(",")
    print(json.dumps(abo))

print('],"id": id}')


标签: pythonjsonpython-3.xfor-looprandom

解决方案


你很接近。声明列表并将数据附加到它。

前任:

from faker import Faker

fake = Faker('en_US')

n = 3
id='123456'
data = { "abo": [], "id": id}        #!Update
for _ in range(n):
    data["abo"].append(              #!Update
        {
            "id": "1ab",
            "data": fake.text(),
            "place": fake.state(),   #!Update
            "user_id": id
            }
        )
print(data)

输出:

{'abo': [{'data': 'Discuss glass trial game physical pressure. Task former '
                  'perhaps suggest your. Some that suddenly family '
                  'organization north assume.',
          'id': '1ab',
          'place': 'Texas',
          'user_id': '123456'},
         {'data': 'Brother energy expect check maybe itself attack. Power size '
                  'we tell.',
          'id': '1ab',
          'place': 'Alaska',
          'user_id': '123456'},
         {'data': 'Result become politics each line price describe. Magazine '
                  'vote society life dark physical although. Position read '
                  'president card away. Since strong opportunity morning '
                  'would.',
          'id': '1ab',
          'place': 'Ohio',
          'user_id': '123456'}],
'id': '123456'}

推荐阅读