How to load JSON data into an A-Frame component?

孤人 提交于 2019-12-12 10:59:03

问题


What's the best way to load a custom JSON file as data into an A-frame component ? For example, the JSON file may contain coordinates of points. I want to load the file as an asset and use the parsed json object in the component.

{"coordinates": [{"x": 0, "y": 1, "z": 2}, // ...]}

回答1:


You can define your own property type in the schema that parses data how you wish.

To parse JSON from a component, create a parse function that does a JSON.parse:

AFRAME.registerComponent('foo', {
  schema: {
    jsonData: {
      parse: JSON.parse,
      stringify: JSON.stringify
    }
  }
});

Then use the component:

el.setAttribute('foo', 'jsonData', yourJsonData);

Or:

<a-entity foo='jsonData: {"coordinates": [{"x": 0, "y": 1, "z": 2}]}'></a-entity>



回答2:


Another way is to set your component to have no schema so it just takes an object. There is no API to have a "wildcard" schema yet, but one way is to have a property type that parses the inline-CSS-like string with the styleParser:

AFRAME.registerComponent('foo', {
  schema: {
    parse: AFRAME.utils.styleParser.parse
  }
});

The above component is a single-property schema, so whatever object we pass will become the value of this.data:

el.setAttribute('foo', {bar: 'baz', qux: 'qaz', whateverWeWant: true});

Or:

<a-entity foo="bar: baz; qux: qaz: whateverWeWant: true"></a-entity>


来源:https://stackoverflow.com/questions/41545518/how-to-load-json-data-into-an-a-frame-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!