JQuery.parseJSON无法使用字符串 [英] JQuery.parseJSON not working with string

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

问题描述

我正在尝试将字符串解析为对象。
我查看了以下链接中的jQueryparseJSON文档
I还包括jquery库,所以我知道它不是。

I am trying to parse a string into an object. I have looked at the jQueryparseJSON documentation at the following link I've also included the jquery library so I know it's not that.

这是我的代码到目前为止

This is my code so far

var str = "{'val1': 1, 'val2': 2, 'val3': 3}";
var obj = jQueryparseJSON( str );
alert(obj.val1);

在Firebug中我收到以下错误:

In Firebug I am getting the following errors:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

我知道解决方案很可能非常简单,但我一再忽略它。

I know the solution is more than likely very simple, but I have been repeatedly overlooking it.

推荐答案

示例代码中的测试字符串无效JSON:

The test string in your sample code is not valid JSON:

var str = '{"val1": 1, "val2": 2, "val3": 3}';
var obj = jQuery.parseJSON( str );
alert(obj.val1);

现在,如果你正在做这一切,因为有些服务正在将该对象作为JSON字符串提供,可能是 jQuery无论如何都会为你做解析步骤的情况。如果您只是想在JavaScript代码中包含一个对象文字,那么就没有理由让JSON服务全部涉及:

Now, if you're doing all this because some service is making that object available as a JSON string, it's probably the case that jQuery will do the parsing step for you anyway. If you're just trying to include an object literal into your JavaScript code, then there's no reason to involve the JSON services at all:

var obj = { val1: 1, val2: 2, val3: 3 };

创建一个对象。

注意JSON语法比JavaScript对象文字语法更严格。 JSON坚持使用双引号字符引用属性名称,当然值只能是数字,字符串,布尔值或 null

Note that JSON syntax is stricter than JavaScript object literal syntax. JSON insists that property names be quoted with double-quote characters, and of course values can only be numbers, strings, booleans, or null.

这篇关于JQuery.parseJSON无法使用字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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