【问题标题】:How to validate this json file into a correct one?如何验证这个 json 文件是否正确?
【发布时间】:2019-06-25 12:02:34
【问题描述】:

此代码使用 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"}

【问题讨论】:

  • 仅供参考,您的预期输出不是 有效 JSON 也

标签: python json python-3.x subprocess delimiter


【解决方案1】:

与其拥有两个脚本,不如在一个脚本中包含执行您需要的事情的函数,也许?

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)

【讨论】:

    【解决方案2】:

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

    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()))
    

    【讨论】:

    • 它会在结尾创建一个额外的,对吗?所以我必须使用正则表达式删除它?
    • 是的,但是如果范围不大,您应该只生成 fake_emails 来列出并将其转储到文件中。简单的编程逻辑就足够了。不需要正则表达式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2013-06-11
    • 2016-10-21
    • 2023-03-17
    • 2023-03-25
    相关资源
    最近更新 更多