如何使用多个对象从json字符串创建JSON对象

时间:2015-03-20 13:18:47

标签: javascript jquery

我有一个像这样的json字符串

{
 [
  {"plan": "basic", "plan_id": "sub33"},
  {"plan": "advanced", "plan_id: "sub44"}
 ]
}

如何从上面创建JSON对象?

当我尝试解析它时,我收到一个错误:

var obj = jQuery.parseJSON( '{[{"plan": "basic", "plan_id": "sub33"},{"plan": "advanced", "plan_id: "sub44"}]}' );
(program):1 Uncaught SyntaxError: Unexpected token [
var obj = jQuery.parse( '{[{"plan": "basic", "plan_id": "sub33"},{"plan": "advanced", "plan_id: "sub44"}]}' );
VM8143:2 Uncaught TypeError: undefined is not a function

3 个答案:

答案 0 :(得分:6)

首先,您需要有效的JSON。您的示例无效,它需要数组的密钥,例如:

{
 "array": [
  {"plan": "basic", "plan_id": "sub33"},
  {"plan": "advanced", "plan_id": "sub44"}
 ]
}

,如果你只想要一个数组而不是它周围的对象包装器:

[
  {"plan": "basic", "plan_id": "sub33"},
  {"plan": "advanced", "plan_id": "sub44"}
]
  

如何从上面创建一个JSON对象?

你还没有,你已经拥有了一个" JSON对象" (文本定义对象)。 JSON是数据交换的文本符号;当你把它变成内存中的对象时,它不再是文本了,所以它不再是JSON了。 (就像DOM元素不是HTML字符串一样,即使它可能是 HTML字符串创建的。)

要将其转换为JavaScript对象,您可以使用JSON.parsejQuery.parseJSON也很好,对于真正的旧浏览器很有用,但现在所有现代浏览器都有JSON.parse

var obj = JSON.parse(yourString);

示例:



var yourString = '{' +
    '"array": ' +
    ' [' +
    '  {"plan": "basic", "plan_id": "sub33"},' +
    '  {"plan": "advanced", "plan_id": "sub44"}' +
    ' ]' +
    '}';
var obj = JSON.parse(yourString);
snippet.log(obj.array[0].plan); // "basic"

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;

或者如果您只是想要数组:

示例:

&#13;
&#13;
var yourString =
    '[' +
    '  {"plan": "basic", "plan_id": "sub33"},' +
    '  {"plan": "advanced", "plan_id": "sub44"}' +
    ']';
var array = JSON.parse(yourString);
snippet.log(array[0].plan); // "basic"
&#13;
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

只需删除过多的{}。并纠正拼写错误“plan_id **”**:

var x = [
  {"plan": "basic", "plan_id": "sub33"},
  {"plan": "advanced", "plan_id": "sub44"}
];

// x是JS对象。 JSON是表示法,而不是构造函数。 您可以通过字符串进行字符串化,例如JSON.stringify(x),这将为您提供一个JSON字符串:“[{”plan“:”basic“,”plan_id“:”sub33“},{”plan“ : “高级”, “plan_id的数据类型”: “sub44”}]“

答案 2 :(得分:-2)

您可以使用JSON.parse(jsonString)