【发布时间】:2017-02-18 17:20:27
【问题描述】:
由于 JSON 无法执行功能,我需要通过 JSON 对象中的键标志来评估 JSON 字符串。我想在 JSON 数据为 Object 形式时对其进行变异。
我在网上找不到可以根据已知键模式为我提供键的完整路径的函数/方法。
鉴于此数据:
{
"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": [...]
}
}
}
标志是以js:开头的键。
如果我查找 js:format,我希望它的路径类似于:/js:bindto 和 /axis/y/tick/js:format。接受建议。
在上下文中:
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;
}
我接触过几个 npm 包:
- object search 无外卡环顾
- dotty 看起来不错,但搜索失败:“*.js:format”
- https://github.com/capaj/object-resolve-path - 需要密钥的完整路径。我事先并不知道。
看过
- JavaScript recursive search in JSON object
- Find property by name in a deep object
- DefiantJS(无 npm 模块)
- https://gist.github.com/iwek/3924925
我没有看到任何东西可以返回相关键的完整路径以便我可以修改它,也不能直接处理对象本身以便我可以更改它的属性。
【问题讨论】:
-
mutateGraphData<T>(data:T):T是什么语言? -
@NinaScholz:打字稿。
标签: javascript json node.js recursion