Skip to content

Commit bef1cb3

Browse files
author
Kazuki Hamasaki
committed
Fixed #57 Add error handling on input the invalid jsonpath syntax
1 parent 6b87545 commit bef1cb3

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

src/App.tsx

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ function App() {
2424
const [result, setResult] = useState(JSON.stringify([], null, 4));
2525
const [resultType, setResultType] = useState<'value' | 'path'>('value');
2626
const [query, setQuery] = useState('$.phoneNumbers[:1].type');
27+
const [isQueryValid, setQueryValid] = useState(true);
28+
const [queryParseError, setQueryParseError] = useState('');
2729

2830
const queryInput = useRef<HTMLInputElement>(null);
2931

@@ -38,23 +40,34 @@ function App() {
3840

3941
function onChangeResultType(event: any) {
4042
const type = event.target.checked ? 'path' : 'value';
41-
setResultType(type)
43+
setResultType(type);
4244
}
4345

4446
function applyJsonPath(jsonStr: string, jsonPath: string) {
4547
let json = '';
48+
let result = '';
49+
4650
try {
4751
json = JSON.parse(jsonStr.replace(/(\r\n|\n|\r)/gm, ''));
4852
} catch (error) {
4953
setResult('JSON Parse Error');
5054
return;
5155
}
5256

53-
const result = JSONPath({
54-
json,
55-
path: jsonPath,
56-
resultType: resultType,
57-
});
57+
try {
58+
result = JSONPath({
59+
json,
60+
path: jsonPath,
61+
resultType: resultType,
62+
});
63+
setQueryValid(true);
64+
setQueryParseError('');
65+
} catch (error) {
66+
setQueryValid(false);
67+
if (error instanceof Error) {
68+
setQueryParseError(error.message);
69+
}
70+
}
5871

5972
if (0 < result.length) {
6073
setResult(JSON.stringify(result, undefined, 2));
@@ -77,7 +90,7 @@ function App() {
7790
<input
7891
id="jsonpath-query"
7992
type="text"
80-
className="form-control"
93+
className={"form-control " + (isQueryValid ? "" : "is-invalid")}
8194
placeholder="Put JSONPath syntax"
8295
value={query}
8396
onInput={onInputQuery}
@@ -86,6 +99,9 @@ function App() {
8699
<label htmlFor="jsonpath-query">
87100
JSONPath
88101
</label>
102+
<div className="invalid-feedback">
103+
{queryParseError}
104+
</div>
89105
</div>
90106

91107
<div className="row py-2">

0 commit comments

Comments
 (0)