python - 使用 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}')
解决方案
你很接近。声明列表并将数据附加到它。
前任:
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'}
推荐阅读
- angular - 通用 SSR Lambda 上未解决 Angular 11 组件
- c++ - 我需要删除重复的顶点(邻接列表)
- javascript - 为什么我来自 HTML/CSS/JS 网站的 CSS 在我的 React 网站上不起作用?
- amazon-web-services - docker context create ecs myecs - 只需要一个参数
- flutter - Flutter Unit Test, Two equal instances are failing
- sql-server - 选择 Top/Last 和 Position 编号 Order By 以及所有列
- algorithm - 排序大小为 n 的数组,数组左侧的元素 n-⌊√n⌋ 已经排序
- python - 当数据框中的日期不连续时,如何使图形的 x 轴连续日期?
- python - Python:如何将 Voronoi 单元扩展到几何边界?
- python - 如何将 Google Colab 与服务器本地运行时连接