JSON字符串转JS对象

发布于 2024-08-21 13:48:13 字数 1607 浏览 3 评论 0 原文

我正在使用 JS 对象通过 Google 可视化创建图表。我正在尝试设计数据源。首先,我在客户端创建了一个 JS 对象。

var JSONObject = {
  cols: [{
      id: 'date',
      label: 'Date',
      type: 'date'
    },
    {
      id: 'soldpencils',
      label: 'Sold Pencils',
      type: 'number'
    },
    {
      id: 'soldpens',
      label: 'Sold Pens',
      type: 'number'
    }
  ],
  rows: [{
      c: [{
        v: new Date(2008, 1, 1),
        f: '2/1/2008'
      }, {
        v: 30000
      }, {
        v: 40645
      }]
    },
    {
      c: [{
        v: new Date(2008, 1, 2),
        f: '2/2/2008'
      }, {
        v: 14045
      }, {
        v: 20374
      }]
    },
    {
      c: [{
        v: new Date(2008, 1, 3),
        f: '2/3/2008'
      }, {
        v: 55022
      }, {
        v: 50766
      }]
    }
  ]
};

var data = new google.visualization.DataTable(JSONObject, 0.5);

现在我需要动态获取数据。因此,我向返回 JSON 字符串的页面发送一个 AJAX 请求:

 "cols: [{id: 'date', label: 'Date', type: 'date'},
{id: 'soldpencils', label: 'Sold Pencils', type: 'number'},
{id: 'soldpens', label: 'Sold Pens', type: 'number'}],
  rows: [{c:[{v: new Date(2008,1,1),f:'2/1/2008'},{v: 30000}, {v: 40645}]},
      {c:[{v: new Date(2008,1,2),f:'2/2/2008'},{v: 14045}, {v: 20374}]},
{c:[{v: new Date(2008,1,3),f:'2/3/2008'},{v: 55022}, {v: 50766}]}"

我将其保存到变量中:

var var1 = "cols: [{i ....... 66}]}"

并显示为

alert(var1);

现在我的任务是从该字符串创建一个 JS 对象。这是行不通的。当我使用 JS 对象时,一切正常,我能够获得所需的图表。现在,如果我尝试将我从警报消息中确认的 AJAX 请求中的相同字符串值放入对象中,则该对象不会正确创建。请让我知道您的意见以及任何更正或建议。

I am using a JS object to create graphs with Google visualization. I am trying to design the data source. At first, I created a JS object client-side.

var JSONObject = {
  cols: [{
      id: 'date',
      label: 'Date',
      type: 'date'
    },
    {
      id: 'soldpencils',
      label: 'Sold Pencils',
      type: 'number'
    },
    {
      id: 'soldpens',
      label: 'Sold Pens',
      type: 'number'
    }
  ],
  rows: [{
      c: [{
        v: new Date(2008, 1, 1),
        f: '2/1/2008'
      }, {
        v: 30000
      }, {
        v: 40645
      }]
    },
    {
      c: [{
        v: new Date(2008, 1, 2),
        f: '2/2/2008'
      }, {
        v: 14045
      }, {
        v: 20374
      }]
    },
    {
      c: [{
        v: new Date(2008, 1, 3),
        f: '2/3/2008'
      }, {
        v: 55022
      }, {
        v: 50766
      }]
    }
  ]
};

var data = new google.visualization.DataTable(JSONObject, 0.5);

Now I need to fetch the data dynamically. So I send an AJAX request to a page that returns the JSON string:

 "cols: [{id: 'date', label: 'Date', type: 'date'},
{id: 'soldpencils', label: 'Sold Pencils', type: 'number'},
{id: 'soldpens', label: 'Sold Pens', type: 'number'}],
  rows: [{c:[{v: new Date(2008,1,1),f:'2/1/2008'},{v: 30000}, {v: 40645}]},
      {c:[{v: new Date(2008,1,2),f:'2/2/2008'},{v: 14045}, {v: 20374}]},
{c:[{v: new Date(2008,1,3),f:'2/3/2008'},{v: 55022}, {v: 50766}]}"

This I save into a variable:

var var1 = "cols: [{i ....... 66}]}"

and show as

alert(var1);

Now my task is to create a JS object from this string. This is not working. When I use a JS object, everything works fine and I am able to get my required graph. Now if I try putting the same value of string from the AJAX request which I confirmed from a alert message into a n object, the object is not getting created correctly. Please let me know your opinion and any correction or advices.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

dawn曙光 2024-08-28 13:48:13

一些现代浏览器支持将 JSON 解析为原生对象:

var var1 = '{"cols": [{"i" ....... 66}]}';
var result = JSON.parse(var1);

对于不支持的浏览器,您可以从 json.org 用于安全解析 JSON 对象。该脚本将检查本机 JSON 支持,如果不存在,则提供 JSON 全局对象。如果更快的本机对象可用,它将退出脚本,使其保持不变。但是,您必须提供有效的 JSON,否则会抛出错误 - 您可以使用 http://jslint.com 检查 JSON 的有效性http://jsonlint.com

Some modern browsers have support for parsing JSON into a native object:

var var1 = '{"cols": [{"i" ....... 66}]}';
var result = JSON.parse(var1);

For the browsers that don't support it, you can download json2.js from json.org for safe parsing of a JSON object. The script will check for native JSON support and if it doesn't exist, provide the JSON global object instead. If the faster, native object is available it will just exit the script leaving it intact. You must, however, provide valid JSON or it will throw an error — you can check the validity of your JSON with http://jslint.com or http://jsonlint.com.

菩提树下叶撕阳。 2024-08-28 13:48:13

如果您信任字符串中的数据,则可以使用 eval(jsonString),否则您需要正确解析它 - 检查 json.org 以获取一些代码示例。

You can use eval(jsonString) if you trust the data in the string, otherwise you'll need to parse it properly - check json.org for some code samples.

猫性小仙女 2024-08-28 13:48:13

您问题中的字符串不是有效的 json 字符串。来自 json.org 网站

JSON 建立在两种结构之上:

* 名称/值对的集合。在各种语言中,这是 
  实现为对象、记录、结构、字典、哈希表、键控列表或
  关联数组。
* 值的有序列表。在大多数语言中,这被实现为
  数组、向量、列表或序列。

基本上,json 字符串始终以 { 或 [ 开头。

然后正如 @Andy E 和 @Cryo 所说,您可以使用 json2.js 或其他一些库来解析字符串。

恕我直言,您应该避免 eval,因为它会影响任何 javascript 程序,因此您可能会遇到安全问题。

the string in your question is not a valid json string. From json.org website:

JSON is built on two structures:

* A collection of name/value pairs. In various languages, this is 
  realized as an object, record, struct, dictionary, hash table, keyed list, or
  associative array.
* An ordered list of values. In most languages, this is realized as an
  array, vector, list, or sequence.

Basically a json string will always start with either { or [.

Then as @Andy E and @Cryo said you can parse the string with json2.js or some other libraries.

IMHO you should avoid eval because it will any javascript program, so you might incur in security issues.

檐上三寸雪 2024-08-28 13:48:13

您可以使用 JSON.org 中的此库来翻译您的字符串转换为 JSON 对象。

var var1_obj = JSON.parse(var1);

或者您也可以使用 jquery-json 库。

var var1_obj = $.toJSON(var1);

You can use this library from JSON.org to translate your string into a JSON object.

var var1_obj = JSON.parse(var1);

Or you can use the jquery-json library as well.

var var1_obj = $.toJSON(var1);
凉墨 2024-08-28 13:48:13

您返回的字符串不是有效的 JSON。对象中的名称需要用引号引起来,并且需要将整个字符串放入 { … } 中以形成对象。 JSON 也不能包含诸如 new Date() 之类的内容。 JSON 只是 JavaScript 的一个小子集,只有字符串、数字、对象、数组、truefalsenull

有关详细信息,请参阅 JSON 语法

The string you are returning is not valid JSON. The names in the objects needs to be quoted and the whole string needs to be put in { … } to form an object. JSON also cannot contain something like new Date(). JSON is just a small subset of JavaScript that has only strings, numbers, objects, arrays, true, false and null.

See the JSON grammar for more information.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文