【问题标题】:Can't access variable in JSON无法访问 JSON 中的变量
【发布时间】:2015-05-21 08:43:19
【问题描述】:

我的 JSONObject 有问题

这是我的代码:

importPackage(Packages.org.apache.commons.io);
importPackage(Packages.java.io);

fisTargetFile = new FileInputStream(new File("C:/moe.json"));
input = IOUtils.toString(fisTargetFile, "UTF-8");

jsonData = input;
myJSONObject = eval('(' + jsonData + ' )');
len = myJSONObject.cells.length;
count = 0;
if (count < len) {
    var name = myJSONObject.cells[count].attrs.text;
    var type = myJSONObject.cells[count].type;
    var photo = myJSONObject.cells[count].attrs.image.xlink:href;
    row["name"] = name;
    row["type"] = type;
// row["photo"]    = photo;
    count++;
    return true;
}
return false;

我的问题出在这一行var photo = myJSONObject.cells[count].attrs.image.xlink:href;

我无法访问我的图像数据,因为这不是正确的语法“:”我该如何克服它?有没有办法逃脱“:”?

编辑: 这是我的 JSON 对象:

{
    "cells": [
    {
        "type": "basic.Platform",
        "size": {
            "width": 60,
            "height": 60
         },
  "custom": {
    "identifier": [
      {
        "name": "Name1",
        "URI": "Value1"
      }
    ],
    "classifier": [
      {
        "name": "Name2",
        "URI": "Value2"
      }
    ],
    "output": [
      {
        "name": "Name3",
        "URI": "Value3"
      }
    ],
    "imported": false,
    "event": [

    ]
  },
  "ref": [

  ],
  "uuid": [
    "dc537ba7-b9dc-476e-9f09-8c1f5211f9bb"
  ],
  "position": {
    "x": 390,
    "y": 230
  },
  "angle": 0,
  "id": "dc537ba7-b9dc-476e-9f09-8c1f5211f9bb",
  "embeds": "",
  "z": 1,
  "description": "",
  "attrs": {
    "text": {
      "font-size": "9",
      "text": "rere",
      "ref-x": "0.5",
      "ref-dy": "20",
      "fill": "#000000",
      "font-family": "Arial",
      "display": "",
      "stroke": "#000000",
      "stroke-width": "0",
      "font-weight": "400"
    },
    "image": {
      "width": 50,
      "height": 50,
      "xlink:href": "data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAG4AAACWCAYAAAA\/mr2PAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS5EOsBjwfqm3fvx0eIfsT89"
    }
  }
}

] }

我已经修剪了 xlink:href 数据,因为它太长了。

【问题讨论】:

  • 如果你能把json文件的内容也贴出来就好了。
  • JSON 是什么样的?为什么需要:
  • 我添加了我的 JSON 对象,我需要检索位于 xlink:href 中的 base64 编码图像,然后将其放入 birt 报告中的表格列中

标签: java javascript json


【解决方案1】:

myJSONObject.cells[count].attrs.image["xlink:href"]

推理:在任何使用点表示法分隔对象引用的地方,您也可以使用方括号表示法并传入一个字符串。这是引用非“有效”标识符(例如名称中间的冒号)的标准方法。

【讨论】:

  • 感谢您的快速回复,非常感谢!它非常适合我。
  • 没问题。很高兴它对你有用,我希望它在未来能解决这些问题:D
【解决方案2】:

在 JavaScript 中,对象也是关联数组(或哈希)。
即属性foo.bar也可以通过调用foo["bar"]来读写

var photo = myJSONObject.cells[count].attrs.image["xlink:href"];

【讨论】:

    【解决方案3】:

    您可以尝试像image["xlink:href"] 的属性一样访问它。

    或者请说明该列代表什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 2017-11-21
      • 2016-07-20
      • 2018-01-10
      • 1970-01-01
      • 2020-12-13
      • 2014-06-04
      相关资源
      最近更新 更多