Skip to content

Instantly share code, notes, and snippets.

@abhijitmamarde
Created December 28, 2020 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhijitmamarde/d11309d4bc8de73acbd373f19651b53f to your computer and use it in GitHub Desktop.
Save abhijitmamarde/d11309d4bc8de73acbd373f19651b53f to your computer and use it in GitHub Desktop.
Get json object from string with an embedded json string
import regex
import json
input_string = '''2020-12-23T07:23:18.000000+05:30 45.79.121.190 {"hostname":"abc.members.linode.com","os":{"name":"CentOS Linux","family":"redhat","version":"7 (Core)","platform":"centos","kernel":"3.10.0-1127.13.1.el7.x86_64","codename":"Core"},"containerized":false,"ip":["44.75.121.190","2400:8904::f03c:92ff:fed4:e4f0","fe80::f03c:92ff:fed4:e4f0"],"name":"abc.members.linode.com","cpu":{"pct":0.062},"id":"c29d751565e74afdbaade6c8a36dd2ef","mac":["f2:3c:92:d4:e4:f0"],"architecture":"x86_64"} LOGSTASH[-]: 2020-12-23T07:23:18.995Z {hostname=abc.members.linode.com, os={name=CentOS Linux, family=redhat, version=7 (Core), platform=centos, kernel=3.10.0-1127.13.1.el7.x86_64, codename=Core}, containerized=false, ip=[44.75.121.190, 2400:8904::f03c:92ff:fed4:e4f0, fe80::f03c:92ff:fed4:e4f0], name=abc.members.linode.com, cpu={pct=0.062}, id=c29d751565e74afdbaade6c8a36dd2ef, mac=[f2:3c:92:d4:e4:f0], architecture=x86_64} %{message}'''
# def get_json2(input_str):
# start = input_str.find('{')
# end = input_str.find('LOGSTASH[')
# try:
# x = input_str[start:end]
# x = json.loads(x)
# return x
# except Exception as err:
# print(f"ERROR not found. start={start}, end={end}, err={err}")
# return {}
# print(get_json2(input_string))
# def get_json(input_str):
# l = []
# for i, c in enumerate(input_str):
# if (c == '{'):
# l.append([c, i])
# if (c == '}'):
# t = l.pop()
# print(f"\n{c} end at {i}, start at: {t}: {input_str[t[1]:i + 1]}")
# try:
# x = json.loads(input_str[t[1]:i + 1])
# if 'hostname' in x:
# print("--- FOUND")
# return x
# except Exception as err:
# print(f"Exception: {err}")
# pass
#
# return {}
# print(get_json(input_string))
pattern = regex.compile(r'\{(?:[^{}]|(?R))*\}')
x = pattern.findall(input_string)
x = json.loads(x[0])
assert 'hostname' in x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment