我有一个输出json的python代码
import json
from faker import Faker
import random
from random import randint
import subprocess
fake = Faker('en_US')
for _ in range(1):
sms = {
"name": fake.name(),
"email": fake.email(),
"location": "usa"
}
with open('abc.json', 'w') as outfile:
json.dump(sms, outfile)
print(sms)
子流程:
x=subprocess.Popen([" python"," first.py"],shell=True, stdout=subprocess.PIPE)
output = x.communicate()
print(output)
我得到的输出:
(b'{\n "name": "elmoroy",\n "email":"ssbyt@gmail.com"}\n', None)
我需要的输出:
{
"name": "elmoroy",
"email":"ssbyt@gmail.com
}
如果我打电话给output["name"]
,它将返回elmoroy
。
答案 0 :(得分:1)
communicate()返回一个元组(stdout_data,stderr_data),所需的输出在output[0]
中,它是所需字典的字符串表示形式,然后可以使用my_dict = json.loads(output[0])
来获取字典。
UPDATE:循环运行
my_dict = {}
for i in range(20):
x=subprocess.Popen([" python"," first.py"],shell=True, stdout=subprocess.PIPE)
output = x.communicate()
my_dict.update({i: json.loads(output[0])})
my_dict
将保存打印的sms
变量的20个字典
答案 1 :(得分:0)
也许您应该尝试使用json.load
,就像这样:
with open('abc.json') as in_file:
obj = json.load(in_file)
print(obj)
请参阅json — JSON encoder and decoder中的“解码JSON”:
---编辑---
尝试一下:
首先,您将获得一个文件,例如:
import json
for _ in range(1):
sms = {
"name": 'some name',
"email": 'some email',
"location": "usa"
}
with open('abc.json', 'w') as outfile:
json.dump(sms, outfile)
然后,您将获得另一个文件,例如:
import json
with open('abc.json') as in_file:
sms = json.load(in_file)
print(sms)
先执行第一个文件,然后执行第二个文件,您可以看到第二个文件将文件内容解析为json对象。