首页 > 解决方案 > 将 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的消息。

标签: javascriptnode.jsjsonosc

解决方案


如果您传递先前遍历的键并向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);


推荐阅读