Since JSON can not perfom functions i need to eval a JSON string by a key flag in the JSON object. I want to mutate the JSON data when it's in Object form.
I can't find a function/method online that can give me the full path to key based on a known key pattern.
Given this data:
{
"js:bindto": "#chart-1", // note the key here 'js:'
"point": {
"r": 5
},
"data": {
"x": "x",
"xFormat": "%Y",
"columns": [
...
],
"colors": {
"company": "#ed1b34",
"trendline": "#ffffff"
}
},
"legend": {
"show": false
},
"axis": {
"x": {
"padding": {
"left": 0
},
"type": "timeseries",
"tick": {
"format": "%Y",
"outer": false
}
},
"y": {
"tick": {
"outer": false,
"js:format": "d3.format(\"$\")" // note the key here 'js:'
}
}
},
"grid": {
"lines": {
"front": false
},
"y": {
"lines": [...]
}
}
}
The flags are keys beginning with js:
.
If I look up js:format
, I'd expect it's path to be something like: /js:bindto
and /axis/y/tick/js:format
. Open to suggestions.
In context:
mutateGraphData<T>(data:T):T {
// data here is a parsed JSON string. ( an object as shown above )
let jsonKeys = this.findKeysInJSON(JSON.stringify(data), "js:");
// jsonKeys = ["js:bindto","js:format"]
jsonKeys.map((key:string) => {
// find the key in data, then modify the value. (stuck here)
// i need the full path to the key so i can change the data property that has the key in question
});
});
return data;
}
findKeysInJSON<T>(jsonString:string, key:string):Array<T> {
let keys = [];
if (Boolean(~(jsonString.indexOf(`"${key}`)))) {
let regEx = new RegExp(key + "(\\w|\\-)+", "g");
keys = jsonString.match(regEx);
}
return keys;
}
I have been around a few npm packages:
- object search no wild card lookaround
- dotty looks good, but fails with search: "*.js:format"
- https://github.com/capaj/object-resolve-path - needs full path to key. I don't know that in advance.
I have looked at
- JavaScript recursive search in JSON object
- Find property by name in a deep object
- DefiantJS ( no npm module )
- https://gist.github.com/iwek/3924925
Nothing have I seen can return the full path to the key in question so I can modify it, nor work directly on the object itself so I can change its properties.