如何验证此 json 文件是否正确?

How to validate this json file into a correct one?

此代码使用 faker 库生成随机 json 数据。

1.py :

import json 
from faker import Faker
import random
from random import randint
import subprocess
fake = Faker('en_US')



for a in range(1):

             abc =  {

            "phone":randint(6666666666,9999999999),
            "name": fake.name(),
            "email": fake.email(),



        }


with open('data.json', 'a+') as outfile:
        json.dump(abc, outfile)

2.py

   for i in range (20):
       subprocess.call(["python","1.py"])

当我打电话给 2.py 时。它将 运行 并使用此

存储输出
 `with open('data.json', 'a+') as outfile:
        json.dump(abc, outfile) `  

所以它存储的是没有分隔符的json,如何存储有效的json。

正在存储的输出:

  {"phone":"944078945","name":"elpeto","email":"asdW@gmail.com"}{"phone":"94407894511","name":"deelpeto","email":"zxcv@gmail.com"}

我需要的出口:

{"phone":"944078945","name":"elpeto","email":"asdW@gmail.com"},{"phone":"94407894511","name":"deelpeto","email":"zxcv@gmail.com"}

只需在转储后手动添加 ","

with open('data.json', 'a+') as outfile:
        json.dump(abc, outfile)
        outfile.write(",")

最后一个不要这样做。

你这样做的方式很奇怪。 open 内的单循环要简单得多,因为打开文件是一项繁重的操作。

def get_abs():
    return {
            "phone":randint(6666666666,9999999999),
            "name": fake.name(),
            "email": fake.email(),
        }

with open('data.json', 'a+') as outfile:
    for abs in range(random_range - 1):
        output_file.write(json.dumps(get_abs()) + ",")
    output_file.write(json.dumps(get_abs()))

与其拥有两个脚本,不如在一个脚本中拥有函数来完成您需要的事情,也许吧?

import json
from faker import Faker
import random

fake = Faker("en_US")


def generate_fake():
    return {
        "phone": randint(6666666666, 9999999999),
        "name": fake.name(),
        "email": fake.email(),
    }


def generate_fakes(n):
    return [generate_fake() for x in range(n)]


def write_fakes(filename, n):
    with open(filename, w) as outfile:
        json.dump(generate_fakes(n), outfile, indent=2)


if __name__ == "__main__":
    write_fakes("data.json", 20)