[英]Generate Random Json data using Python and store in a varaible
我的應用程序采用這種格式的 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
}
如何從此格式生成隨機數據並將它們存儲在給定范圍的變量中?
如果 range 給出為 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}')
你很接近。 向其聲明列表和 append 數據。
前任:
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)
Output:
{'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'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.