如何 json 解析 python 输出并将其值存储在字典或变量中?
how to json parse a python output and store its values like in dict or variables?
我有一个 python 代码输出 json
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"]
它应该 return elmoroy
.
也许你应该尝试使用 json.load
,像这样:
with open('abc.json') as in_file:
obj = json.load(in_file)
print(obj)
参考json — JSON encoder and decoder中的'Decoding 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对象。
communicate() returns一个元组(stdout_data,stderr_data),你需要的输出在output[0]
中,它是你需要的字典的字符串表示,然后您可以使用 my_dict = json.loads(output[0])
来获取字典。
更新:运行 循环
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 个词典
我有一个 python 代码输出 json
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"]
它应该 return elmoroy
.
也许你应该尝试使用 json.load
,像这样:
with open('abc.json') as in_file:
obj = json.load(in_file)
print(obj)
参考json — JSON encoder and decoder中的'Decoding 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对象。
communicate() returns一个元组(stdout_data,stderr_data),你需要的输出在output[0]
中,它是你需要的字典的字符串表示,然后您可以使用 my_dict = json.loads(output[0])
来获取字典。
更新:运行 循环
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
变量