jsoncrawler
jsoncrawler is a simple module that search/replace data inside complex javascript objects
Getting started
Add script tag in your header
<script src="https://cdn.jsdelivr.net/npm/jsoncrawler@latest/jsoncrawler.js"></script>
Or on node.js or webpack based projects:
npm i jsoncrawler
And in your javascript:
import jsonCrawler from 'jsoncrawler';
Parameters
function jsonCrawler(
object_to_search: {[key:string]: any} | any[],
value_to_search: Array<number | string | boolean>,
options: {
replace: Array<number | string | boolean>, // Value to replace. Must be in the same order as the search array.
filter: Array<number | string> // Key names or index numbers to exclude from search/replacement
}): {
path: Array<number | string>,
key: string | number,
siblings: Array<number | string>,
value: number | string | boolean
}[]
Full scan
You can scan the whole object and get the key path, key name, siblings and value
Example
let obj = {
artist: "DIA",
tracks: [
"Paradise",
{
hidden: "Come On Down"
}
]
}
let result = jsonCrawler(obj);
Searching value
Search and locate value inside complex json object
Example
let obj = {
artist: "DIA",
tracks: [
"Paradise",
{
hidden: "Come On Down"
}
]
}
let result = jsonCrawler(obj, ["Come On Down", "DIA"]);
let ComeOnDown = obj;
result[1].path.forEach(p => {
ComeOnDown = ComeOnDown[p];
});
ComeOnDown = ComeOnDown[result[1].key];
let DIA = obj;
result[0].path.forEach(p => {
DIA = DIA[p];
});
DIA = DIA[result[0].key];
Replacing value
You can replace the value easily
Example
let replace = ['Linux', 'Ubuntu', ['Mint', {mini: ['Lubuntu', 'linux']}]];
jsonCrawler(replace, ['Lubuntu', 'Linux'], {
replace: ['Xubuntu', 'Linus']
});
console.log(replace);
Filtering keys
You can exclude your search/replacement in certain key names or index numbers
Example
let replace = ['Linux', 'Ubuntu', ['Mint', {mini: ['Lubuntu', 'linux']}]];
jsonCrawler(replace, ['Lubuntu', 'Linux'], {
replace: ['Xubuntu', 'Linus'],
filter: ['mini']
});
console.log(replace);