-------------------- Takes a list of dictionaries (default return from DQL query) and transforms to a list of CSV rows, preceded with a header row. Args: list_of_dicts (list): A list of dictionary items, i.e., rows of JSON columns. Returns: bool: su
(self, list_of_dicts:list)
| 184 | |
| 185 | |
| 186 | def json_to_csv(self, list_of_dicts:list) -> list: |
| 187 | """-------------------- |
| 188 | Takes a list of dictionaries (default return from DQL query) and transforms to a list of CSV rows, preceded with a header row. |
| 189 | |
| 190 | Args: |
| 191 | list_of_dicts (list): A list of dictionary items, i.e., rows of JSON columns. |
| 192 | |
| 193 | Returns: |
| 194 | bool: success flag |
| 195 | list: A list of CSV strings, i.e., rows of CSV values plus a header row (len(list) will always be N+1) |
| 196 | """ |
| 197 | if list_of_dicts == []: return False, [] |
| 198 | try: |
| 199 | rows = [','.join( list(list_of_dicts[0].keys()) )] # headers |
| 200 | for row in list_of_dicts: |
| 201 | rows.append( ','.join([f'"{str(val).replace(chr(34),chr(34)+chr(34))}"' for val in list(row.values())]) ) |
| 202 | self.logger.debug('Query JSON transformed to CSV') |
| 203 | return True, rows |
| 204 | except Exception as ex: |
| 205 | self.logger.error(f'Query JSON could not be transformed to CSV: {ex}') |
| 206 | return False, None |
| 207 | |
| 208 | |
| 209 | def json_to_dataframe(self, list_of_dicts:list) -> pd.DataFrame: |