JS对象的JSON字符串 [英] JSON string to JS object

查看:122
本文介绍了JS对象的JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JS对象使用Google可视化创建图形。我正在尝试设计数据源。起初,我创建了一个JS对象客户端。

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);

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

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}]}"

并显示为

alert(var1);

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

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.

推荐答案

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

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

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

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

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.

这篇关于JS对象的JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆