need help with parser to make flat nested json list of dictionaries
hi all i have a json message that contains a nested json list of dicts {"a":1,"b":[{"c":1},{"c":2},{"c":3}]} i want to flat that message, so expected result looks like { "a": 1, "b_0_c": 1, "b_1_c": 2, "b_2_c": 3 } My approach is a python implemented parser. Is it possible to achieve the same result using the built-in syslog-ng tools? My solution below @define kafka-implementation kafka-c python { import collections import json class FlattenedJson(object): def parse(self, log_message, flat_message=None): def flatten(d, parent_key='', sep='_'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections.MutableMapping): items.extend(flatten(v, new_key, sep=sep).items()) elif isinstance(v, list): for idx, value in enumerate(v): items.extend(flatten(value, new_key + sep + str(idx), sep).items()) else: items.append((new_key, v)) return dict(items) try: decoded_msg = json.loads(log_message['MESSAGE'].decode('utf-8')) flat_message = flatten(decoded_msg) final_message = str(json.dumps(flat_message)).encode(encoding='utf-8') log_message['MESSAGE'] = final_message except Exception as error: log_message['python_error'] = 'An exception occurred: {}'.format(error) return True }; destination d_kafka_dnstap { kafka( topic("mytopic") bootstrap-servers("localhost:9092") message("$(format-flat-json --scope all-nv-pairs application_name=myapp @timestamp=${ISODATE} )") ); }; source s_net_dnstap { network( transport(udp) port(514) flags(no-parse) ); }; parser p_dnstap { channel { parser { python(class("FlattenedJson")); }; parser { json-parser(prefix("dnstap.")); }; }; }; log { source(s_net_dnstap); parser(p_dnstap); destination(d_kafka_dnstap); };
Hello, If the underlines are not a must in the key, yes you can use *format-flat-json* (it uses dot instead of underscore). It uses the same syntax as format-json. -- Kokan ________________________________________ From: syslog-ng <syslog-ng-bounces@lists.balabit.hu> on behalf of Александр Масленников <alexander.a.maslennikov@gmail.com> Sent: 10 June 2022 10:02 To: syslog-ng@lists.balabit.hu Subject: [syslog-ng] need help with parser to make flat nested json list of dictionaries CAUTION: This email originated from outside of the organization. Do not follow guidance, click links, or open attachments unless you recognize the sender and know the content is safe. hi all i have a json message that contains a nested json list of dicts {"a":1,"b":[{"c":1},{"c":2},{"c":3}]} i want to flat that message, so expected result looks like { "a": 1, "b_0_c": 1, "b_1_c": 2, "b_2_c": 3 } My approach is a python implemented parser. Is it possible to achieve the same result using the built-in syslog-ng tools? My solution below @define kafka-implementation kafka-c python { import collections import json class FlattenedJson(object): def parse(self, log_message, flat_message=None): def flatten(d, parent_key='', sep='_'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections.MutableMapping): items.extend(flatten(v, new_key, sep=sep).items()) elif isinstance(v, list): for idx, value in enumerate(v): items.extend(flatten(value, new_key + sep + str(idx), sep).items()) else: items.append((new_key, v)) return dict(items) try: decoded_msg = json.loads(log_message['MESSAGE'].decode('utf-8')) flat_message = flatten(decoded_msg) final_message = str(json.dumps(flat_message)).encode(encoding='utf-8') log_message['MESSAGE'] = final_message except Exception as error: log_message['python_error'] = 'An exception occurred: {}'.format(error) return True }; destination d_kafka_dnstap { kafka( topic("mytopic") bootstrap-servers("localhost:9092") message("$(format-flat-json --scope all-nv-pairs application_name=myapp @timestamp=${ISODATE} )") ); }; source s_net_dnstap { network( transport(udp) port(514) flags(no-parse) ); }; parser p_dnstap { channel { parser { python(class("FlattenedJson")); }; parser { json-parser(prefix("dnstap.")); }; }; }; log { source(s_net_dnstap); parser(p_dnstap); destination(d_kafka_dnstap); };
participants (2)
-
Peter Kokai (pkokai)
-
Александр Масленников