首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >访问嵌入式JSON的深层对象成员

访问嵌入式JSON的深层对象成员
EN

Stack Overflow用户
提问于 2018-12-18 01:04:22
回答 2查看 87关注 0票数 1

下面的函数做了一个惊人的工作,用一个点标记的字符串来检索深度对象键值:

代码语言:javascript
运行
复制
function getPathValue(obj, path) {
  return new Function('_', 'return _.' + path)(obj);
}

例如,它使用以下内容作为路径参数返回类似于"bar“的键的值:

代码语言:javascript
运行
复制
'data.abc.foo.bar'

但是,一些API将额外字符串JSON打包成一些键值。

我正在寻找对上述函数的增强,以处理这种情况。

例如,Stack自己的WebSocket服务:

代码语言:javascript
运行
复制
wss://qa.sockets.stackexchange.com/

返回如下字符串:

代码语言:javascript
运行
复制
{"action":"155-questions-active","data":"{\"siteBaseHostAddress\":\"stackoverflow.com\",\"id\":53819390,\"titleEncodedFancy\":\"Should I start with webGL1 or webGL2 when using Three.js\",\"bodySummary\":\"Spent some time learning and understanding the basics of webGL and I'm now diving into Three.js.\\n\\nI noticed that I have the option of using webGL1 or webGL2. Seems as if webGL1 is the default, however ...\",\"tags\":[\"three.js\",\"webgl\"],\"lastActivityDate\":1545064508,\"url\":\"https://stackoverflow.com/questions/53819390/should-i-start-with-webgl1-or-webgl2-when-using-three-js\",\"ownerUrl\":\"https://stackoverflow.com/users/8226111/romanrogers\",\"ownerDisplayName\":\"romanrogers\",\"apiSiteParameter\":\"stackoverflow\"}"}

并且我希望能够使用上面的函数来检索具有如下输入字符串的值:

代码语言:javascript
运行
复制
'data.bodySummary'

也许输入字符串可能类似于:

代码语言:javascript
运行
复制
'data/bodySummary'

其中solidus (/slash)表示JSON.parse()。

注意,这需要是动态的,因为我希望在一般情况下,最终用户可以选择任意键来返回值。

EN

Stack Overflow用户

发布于 2018-12-18 01:44:24

下面是一个函数,它将对象或JSON字符串作为第一个参数,将键路径字符串或数组作为第二个参数,然后使用键路径递归遍历对象。

代码语言:javascript
运行
复制
let object = {"action":"155-questions-active","data":"{\"siteBaseHostAddress\":\"stackoverflow.com\",\"id\":53819390,\"titleEncodedFancy\":\"Should I start with webGL1 or webGL2 when using Three.js\",\"bodySummary\":\"Spent some time learning and understanding the basics of webGL and I'm now diving into Three.js.\\n\\nI noticed that I have the option of using webGL1 or webGL2. Seems as if webGL1 is the default, however ...\",\"tags\":[\"three.js\",\"webgl\"],\"lastActivityDate\":1545064508,\"url\":\"https://stackoverflow.com/questions/53819390/should-i-start-with-webgl1-or-webgl2-when-using-three-js\",\"ownerUrl\":\"https://stackoverflow.com/users/8226111/romanrogers\",\"ownerDisplayName\":\"romanrogers\",\"apiSiteParameter\":\"stackoverflow\"}"};

function asObject(str) {
    try {
        return JSON.parse(str);
    } catch (e) {
        return str;
    }
}


function valueAtKeyPath(o, path) {
    o = asObject(o);
    if (typeof path === 'string') path = path.split('.');
    
    if (!o || !path.length) return o;
    return valueAtKeyPath(o[path[0]], path.slice(1));
}

console.log(valueAtKeyPath(object, 'action'))
console.log(valueAtKeyPath(object, 'data.id'))

票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53819904

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档