Skip to content

Instantly share code, notes, and snippets.

@sheepla
Created August 25, 2024 06:15
Show Gist options
  • Select an option

  • Save sheepla/3090c35346628e10d4fc2b785a814529 to your computer and use it in GitHub Desktop.

Select an option

Save sheepla/3090c35346628e10d4fc2b785a814529 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find Text from JSON</title>
</head>
<body>
<h1>Find Text from JSON</h1>
<textarea id="jsonInput" rows="10" cols="50" placeholder="Enter JSON here..."></textarea><br>
<input type="text" id="keyword" placeholder="Enter keyword...">
<button onclick="search()">Search</button>
<h2>Results</h2>
<pre id="results"></pre>
<script>
function search() {
const jsonInput = document.getElementById('jsonInput').value;
const keyword = document.getElementById('keyword').value;
try {
const json = JSON.parse(jsonInput);
const results = findMatchingValues(json, keyword);
document.getElementById('results').textContent = JSON.stringify(results, null, 2);
} catch (e) {
document.getElementById('results').textContent = 'Invalid JSON input';
}
}
function findMatchingValues(json, keyword, path = '') {
let results = [];
if (typeof json === 'object' && json !== null) {
if (Array.isArray(json)) {
for (let i = 0; i < json.length; i++) {
results = results.concat(findMatchingValues(json[i], keyword, `${path}[${i}]`));
}
} else {
for (let key in json) {
if (json.hasOwnProperty(key)) {
const newPath = path ? `${path}.${key}` : key;
if (typeof json[key] === 'string' && json[key].includes(keyword)) {
results.push({ value: json[key], path: newPath });
} else {
results = results.concat(findMatchingValues(json[key], keyword, newPath));
}
}
}
}
}
return results;
}
</script>
</body>
</html>
@sheepla

sheepla commented Aug 25, 2024

Copy link
Copy Markdown
Author

image

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