From bef1cb3b8eb5b70d1a04f3fb5f0a248a12762bc1 Mon Sep 17 00:00:00 2001 From: Kazuki Hamasaki Date: Thu, 24 Mar 2022 18:39:17 +0900 Subject: [PATCH] Fixed #57 Add error handling on input the invalid jsonpath syntax --- src/App.tsx | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index d275936..dce45c7 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -24,6 +24,8 @@ function App() { const [result, setResult] = useState(JSON.stringify([], null, 4)); const [resultType, setResultType] = useState<'value' | 'path'>('value'); const [query, setQuery] = useState('$.phoneNumbers[:1].type'); + const [isQueryValid, setQueryValid] = useState(true); + const [queryParseError, setQueryParseError] = useState(''); const queryInput = useRef(null); @@ -38,11 +40,13 @@ function App() { function onChangeResultType(event: any) { const type = event.target.checked ? 'path' : 'value'; - setResultType(type) + setResultType(type); } function applyJsonPath(jsonStr: string, jsonPath: string) { let json = ''; + let result = ''; + try { json = JSON.parse(jsonStr.replace(/(\r\n|\n|\r)/gm, '')); } catch (error) { @@ -50,11 +54,20 @@ function App() { return; } - const result = JSONPath({ - json, - path: jsonPath, - resultType: resultType, - }); + try { + result = JSONPath({ + json, + path: jsonPath, + resultType: resultType, + }); + setQueryValid(true); + setQueryParseError(''); + } catch (error) { + setQueryValid(false); + if (error instanceof Error) { + setQueryParseError(error.message); + } + } if (0 < result.length) { setResult(JSON.stringify(result, undefined, 2)); @@ -77,7 +90,7 @@ function App() { JSONPath +
+ {queryParseError} +