Skip to content

Commit

Permalink
Fixed #57 Add error handling on input the invalid jsonpath syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
Kazuki Hamasaki committed Mar 24, 2022
1 parent 6b87545 commit bef1cb3
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLInputElement>(null);

Expand All @@ -38,23 +40,34 @@ 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) {
setResult('JSON Parse Error');
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));
Expand All @@ -77,7 +90,7 @@ function App() {
<input
id="jsonpath-query"
type="text"
className="form-control"
className={"form-control " + (isQueryValid ? "" : "is-invalid")}
placeholder="Put JSONPath syntax"
value={query}
onInput={onInputQuery}
Expand All @@ -86,6 +99,9 @@ function App() {
<label htmlFor="jsonpath-query">
JSONPath
</label>
<div className="invalid-feedback">
{queryParseError}
</div>
</div>

<div className="row py-2">
Expand Down

0 comments on commit bef1cb3

Please sign in to comment.