Created
August 25, 2024 06:15
-
-
Save sheepla/3090c35346628e10d4fc2b785a814529 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!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
commented
Aug 25, 2024
Author

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