I got the following problem with Python.
given the following JSON object - I would like to
- read this json as a dict
- take several of the keys and put them as a header in a CSV file like so:
CSV headers
firstName,lastName,managersEmail,contractStartsDate
- put the corresponding values of those keys inside the CSV as rows like so:
CSV contents
firstName,lastName,managersEmail,contractStartsDate
nameOfPerson,lastNameofPerson,someManager,2000-01-01
nameOfPerson2,lastNameofPerson2,someManager2,2000-02-02
- do not duplicate any keys inside the CSV
- but put each value from each key out of the JSON inside the CSV under the corresponding header value
my targetJSON.json
data = '{"details":[
{"firstName":"nameOfPerson,"lastName":"lastNameofPerson","managersEmail":"someEmail","managersName":"someManager",
"departmentName":"someDepartment",
"position":"somePosition",
"contractStartsDate":"2000-01-01",
"contractEndDate":"2000-01-01",
"company":"someCompany",
"division":"someDivision",
"preferredName":"Unknown"},
{"firstName":"nameOfPerson2","lastName":"lastNameofPerson2","managersEmail":"someEmail2","managersName":"someManager2",
"departmentName":"someDepartment2",
"position":"somePosition2",
"contractStartsDate":"2000-02-02",
"contractEndDate":"2000-02-02",
"company":"someCompany",
"division":"someDivision2",
"preferredName":"Unknown"}
]}'
My code looks like this
with open('targetJSON.json', 'r') as f:
distros_dict = json.load(f)
for distro in distros_dict:
print(distro['managersEmail'])
data_file = open("targetJSON.json", "r")
values = json.load(data_file)
data_file.close()
with open("usersData.csv", "wb") as f:
wr = csv.writer(f)
for data in values:
value = data["managersEmail"]
value = data["firstName"]
for key, value in data.iteritems():
#wr.writerow([key, value])
wr.writerow([key.encode("utf-8"), value.encode("utf-8")])
But the results is complete gibberish, the CSV contains everything mixed up :-(