-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
135 lines (118 loc) · 5.7 KB
/
app.py
File metadata and controls
135 lines (118 loc) · 5.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
from flask import Flask, render_template, request, jsonify
import json
import re
app = Flask(__name__)
# Path format configurations
PATH_FORMATS = {
'postgresql': {'separator': '->', 'key_format': "'{}'", 'index_format': '{}', 'prefix': ''},
'javascript': {'separator': '.', 'key_format': '{}', 'index_format': '[{}]', 'prefix': ''},
'python': {'separator': '', 'key_format': "['{}']", 'index_format': '[{}]', 'prefix': ''},
'jsonpath': {'separator': '.', 'key_format': '{}', 'index_format': '[{}]', 'prefix': '$'}
}
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
@app.route('/format_json', methods=['POST'])
def format_json():
try:
data = request.json.get('data', '')
if not data.strip():
return jsonify({'error': 'No JSON data provided'}), 400
parsed = json.loads(data)
formatted_json = json.dumps(parsed, indent=2)
return jsonify({'formatted': formatted_json, 'valid': True})
except json.JSONDecodeError as e:
error_msg = f"Invalid JSON at line {e.lineno}, column {e.colno}: {e.msg}"
return jsonify({'error': error_msg, 'line': e.lineno, 'column': e.colno}), 400
@app.route('/validate_json', methods=['POST'])
def validate_json():
"""Validate JSON without formatting - returns validation status"""
try:
data = request.json.get('data', '')
if not data.strip():
return jsonify({'valid': False, 'error': 'No JSON data provided'})
json.loads(data)
return jsonify({'valid': True})
except json.JSONDecodeError as e:
error_msg = f"Line {e.lineno}, column {e.colno}: {e.msg}"
return jsonify({'valid': False, 'error': error_msg, 'line': e.lineno, 'column': e.colno})
@app.route('/search_json', methods=['POST'])
def search_json():
data = request.json.get('data', '')
search_term = request.json.get('search_term', '').lower()
path_format = request.json.get('path_format', 'postgresql')
custom_config = request.json.get('custom_config', None)
if not data.strip():
return jsonify({'error': 'No JSON data provided'}), 400
if not search_term:
return jsonify({'error': 'No search term provided'}), 400
# Use custom config if provided, otherwise use preset formats
if path_format == 'custom' and custom_config:
format_config = {
'separator': custom_config.get('separator', '->'),
'key_format': custom_config.get('key_format', "'{}'"),
'index_format': custom_config.get('index_format', '{}'),
'prefix': custom_config.get('prefix', '')
}
else:
format_config = PATH_FORMATS.get(path_format, PATH_FORMATS['postgresql'])
def format_path(path_parts):
"""Convert path parts to the selected format"""
if not path_parts:
return format_config['prefix'] or 'root'
result = format_config['prefix']
for i, part in enumerate(path_parts):
if part['type'] == 'key':
formatted_part = format_config['key_format'].format(part['value'])
else: # index
formatted_part = format_config['index_format'].format(part['value'])
# Add separator logic
if format_config['separator'] and result and result != format_config['prefix']:
# For formats like python where index doesn't need separator
if path_format == 'python' or (path_format in ['javascript', 'jsonpath'] and part['type'] == 'index'):
result += formatted_part
else:
result += format_config['separator'] + formatted_part
else:
result += formatted_part
return result
def search_with_path(obj, term, path=None):
results = []
matches = []
if path is None:
path = []
if isinstance(obj, dict):
for key, value in obj.items():
new_path = path + [{'type': 'key', 'value': key}]
if term in key.lower():
results.append({'path': format_path(new_path)})
matches.append({'value': key, 'path': format_path(new_path)})
if isinstance(value, (dict, list)):
sub_results, sub_matches = search_with_path(value, term, new_path)
results.extend(sub_results)
matches.extend(sub_matches)
elif term in str(value).lower():
results.append({'path': format_path(new_path)})
matches.append({'value': str(value), 'path': format_path(new_path)})
elif isinstance(obj, list):
for i, item in enumerate(obj):
new_path = path + [{'type': 'index', 'value': i}]
if isinstance(item, (dict, list)):
sub_results, sub_matches = search_with_path(item, term, new_path)
results.extend(sub_results)
matches.extend(sub_matches)
elif term in str(item).lower():
results.append({'path': format_path(new_path)})
matches.append({'value': str(item), 'path': format_path(new_path)})
return results, matches
try:
json_data = json.loads(data)
search_results, matches = search_with_path(json_data, search_term)
return jsonify({'results': search_results, 'matches': matches})
except json.JSONDecodeError as e:
error_msg = f"Invalid JSON at line {e.lineno}, column {e.colno}: {e.msg}"
return jsonify({'error': error_msg}), 400
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)