I am getting some json from an api, and with the json response i am writing the data to a csv file. some of the json keys are numbers(actually strings but can be converted) and some of them are strings. If they are numbers I need to convert them to an actual name. I have an xml file as a look up table of sort and I am getting some errors on getting the text from a xml field.
.json file
[
{
"id": "228",
"fullName2": "users name",
"4600.0": "0000-00-00",
"4600.2": "some text",
}
]
columnLookup.xml file as a look up table
<data>
<fields>
<field id="NA" alias="fullName2">full name</field>
<field id="15493" alias="id">id</field>
<field id="4600.0" alias="jobTitle">Job Title</field>
</fields>
</data>
.py file Mycode
def write_to_csv_file(self):
with open(self.mJSON_file_name) as json_file:
data = json.load(json_file)
csv_file = open(self.mCSV_file_name, 'w')
csv_writer = csv.writer(csv_file)
count = 0
keys_dict = {}
for emp in data:
if count == 0:
header = emp.keys()
for key in header:
headers = get_name_from_id(key)
keys_dict[headers] = ''
csv_writer.writerow(keys_dict.keys())
count += 1
csv_writer.writerow(emp.values())
csv_file.close()
self.mCSV_data = csv_file
def get_name_from_id( search_id):
query = 'field[@id="{}"]'.format(search_id)
alias_query = 'field[@alias="{}"]'.format(search_id)
tree = ET.parse('columnLookup.xml')
root = tree.getroot()
for data in root.iter('fields'):
if search_id.isdigit():
return data.find(query).text
else:
return data.find(alias_query).text
explenation:
basically I get that key from the json file and pass it to the get_name_from_id() function. if it can be converted to a digit. I look up the id of the value in the xml file and return the text. If it cant be converted to a digit, then I look up the text value from the alias of a field. im crashing on "fullName2".
when the key from the json file is "fullName2", I need it to find the field in the xml file with alias="fullName2" and then return the text "full name". any ideas why im getting the attribute error?
query = '//field[@id="{}"]'.format(search_id)that is a relative path lookup.Noneand try to doNone.text. First you should getitem = data.find(query)anditem = data.find(alias_query)and check ifitmeis notNoneand then usereturn item.text.for-loop is wrong - you havereturninifandelseso it exits function on first elementfields.'.//field[@id="{}"]'- to make it relative todata