Skip to content

Instantly share code, notes, and snippets.

@gelbermann
Last active September 1, 2023 07:45
Show Gist options
  • Save gelbermann/7719f414dc3558b7263b0b564f8145a9 to your computer and use it in GitHub Desktop.
Save gelbermann/7719f414dc3558b7263b0b564f8145a9 to your computer and use it in GitHub Desktop.
Convert Java `toString()` output to JSON
import json
import sys
def parse_json_value(value):
try:
json_value = json.loads(value)
return json_value
except json.JSONDecodeError:
return value
def is_json(value):
return (value.startswith('{') and value.endswith('}')) or (value.startswith('[') and value.endswith(']'))
def inside_structure(edge_char_count):
return edge_char_count != 0
def split_into_pairs(java_string):
pairs = []
current_key = ""
current_value = ""
braces_count = 0
brackets_count = 0
inside_value = False
for char in java_string:
if char == '=' and not inside_structure(braces_count) and not inside_structure(brackets_count):
current_key = current_key.strip()
inside_value = True
elif char == ',' and not inside_structure(braces_count) and not inside_structure(brackets_count):
current_value = current_value.strip()
if current_key:
pairs.append((current_key, current_value))
current_key = ""
current_value = ""
inside_value = False
elif char == '{':
braces_count += 1
elif char == '}':
braces_count -= 1
elif char == '[':
brackets_count += 1
elif char == ']':
brackets_count -= 1
if inside_value:
current_value += char if char != '=' else ''
elif char != '=':
current_key += char if char != ',' else ''
if current_key:
current_value = current_value.strip()
pairs.append((current_key, current_value))
return pairs
def java_to_json(java_string):
pairs = split_into_pairs(java_string)
# Create a dictionary to store key-value pairs
data = {}
for key, value in pairs:
if is_json(value):
json_value = parse_json_value(value)
data[key] = json_value
else:
data[key] = value.strip()
return json.dumps(data, indent=2)
if len(sys.argv) < 2:
print("Usage: python java_tostring_to_json.py 'java_output'")
sys.exit(1)
java_output = sys.argv[1]
# Convert and print as JSON
json_output = java_to_json(java_output)
print(json_output)
@gelbermann
Copy link
Author

How to use

POJO-generated strings have a wrapper around the content of the class, with the class's name and brackets, in this format:

MyPojoClass[<class_content>]

To use the script you must remove this wrapper, and call the script like this (must add the quote marks):

python java_tostring_to_json.py '<class_content>'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment