javascript - 将 json 转换为 osc 地址和参数
问题描述
我正在尝试在 javascript 中创建一个通用函数,它将 json 数据结构转换为OSC兼容格式。OSC 表示分配给任何类型参数的“/”分隔地址字符串。
像这样的嵌套 json:
{
"hello":"world",
"one":{
"two":{
"three":[4, 5, 6, 7]
},
"deux":"trois",
"zwei":3
}
}
会导致:
[
{
"addr":"/hello",
"args":"world"
},
{
"addr":"/one/two/three",
"args":[4, 5, 6, 7]
},
{
"addr":"/one/deux",
"args":"trois"
},
{
"addr":"/one/zwei",
"args":3
},
]
我不是递归函数的粉丝,但我认为这是唯一的方法,所以我想出了这个:
example = {
"hello":"world",
"one":{
"two":{
"three":[4, 5, 6, 7]
},
"deux":"trois",
"zwei":3
}
}
toOSC(example)
function toOSC(json) {
var osc_msg = [{address:""}]
createPath(json, osc_msg,0,"")
for(let o of osc_msg) {
if(o.hasOwnProperty('args')) {
console.log(o)
}
}
}
function createPath(obj, osc_msg, i, addr) {
for(let m in obj) {
osc_msg[i]['address'] += '/' + m
if(Array.isArray(obj[m]) || typeof obj[m] !== 'object') {
osc_msg[i]['args'] = obj[m]
i++
osc_msg.push({address:""})
} else {
i = createPath(obj[m], osc_msg, i, osc_msg[i].address)
i++
osc_msg.push({address:addr})
}
}
return i
}
代码失败的方式是两个相同深度的嵌套对象中的第二个,摆脱了其地址的第一部分,我无法理解它。
我很高兴有任何想法,以及将 json 转换为 OSC 兼容格式的一般方法。
我想使用转换来发送带有 node.js 包osc-min的消息。
解决方案
如果您传递先前遍历的键并向yield
上传递结果,则会更容易:
function* format(obj, previous = "") {
for(const [key, value] of Object.entries(obj)) {
if(typeof value !== "object" || Array.isArray(value)) {
yield { addr: previous + "/" + key, args: value };
} else {
yield* format(value, previous + "/" + key);
}
}
}
// That can be used as:
const result = [...format({ a: { b: "test", d: { e: 1 }}, c: [1, 2, 3] })];
console.log(result);
推荐阅读
- ios - 无法在 swift ui 中单击分段选择器
- plantuml - PlantUML 中是否有可用于进一步处理的中间表示?
- reactjs - 如何在 fire base 实时数据库中引入手动创建的 json 数组并将其保存为我的 react native 项目中的变量?
- css - 如何在 Bootstrap AdminLTE 3 主题中更改登录页面的背景颜色
- c - 省略号在特别是在 c 中的可用性
- angular - 如何为 Angular 应用程序提供单独的 login.html 页面
- wordpress - 当我重新启动我的 ec2 实例时,没有在 AWS 上托管的 wordpress 网站上上传图片
- reactjs - 嗨,我正在寻找在页面导航时保持排序/分页状态
- python - 为什么我的代码给出 TypeError: TypeError: 'int' object has no attribute '__getitem__'?
- flutter - 如何与 moor 一起实施 Change Notifier?