how to json parse a python output and store its values like in dict or variables?

Viewed 4942

I have a python code that outputs 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)

subprocess:

x=subprocess.Popen([" python"," first.py"],shell=True, stdout=subprocess.PIPE)
output = x.communicate()
print(output)

output I am getting :

(b'{\n  "name": "elmoroy",\n  "email":"ssbyt@gmail.com"}\n', None)

output I need :

{
"name": "elmoroy",
"email":"ssbyt@gmail.com
}

If I call output["name"] it should return elmoroy.

2 Answers

communicate() returns a tuple (stdout_data, stderr_data), the output you need is in output[0] which is a string representation of the dictionary you need, you can then use my_dict = json.loads(output[0]) to get a dictionary.

UPDATE : to run this in a loop

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 would hold 20 dictionaries of the printed sms variable

Maybe you should try using json.load, like this:

with open('abc.json') as in_file:
    obj = json.load(in_file)
print(obj)

Refer to 'Decoding JSON' in json — JSON encoder and decoder:

---edit---

Try this:

First, you get a file like:

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)

Then, you get another file like:

import json

with open('abc.json') as in_file:
    sms = json.load(in_file)
print(sms)

Execute first file and then the second, and you can see the second file parse the file content into a json object.

Related