I want to make JSON array using jQuery and got some problem:
<html>
<head>
<title>Demo - Push Data Object</title>
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
<script>
var obj = new Object();
$(document).ready(function() {
$("#add").click(function() {
item('Item 1', '1000');
item('Item 2', '2000');
console.log(JSON.stringify(obj));
});
});
function item(itemNo, price) {
obj.itemNo = itemNo;
obj.price = price;
};
</script>
</head>
<body>
<input id="add" type="button" value="Add Object" />
</body>
</html>
When the button add is click it will print:
{"itemNo":"Item 2","price":"2000"}.
What I want to achieve is like this one:
{
{
"itemNo":"Item 1",
"price":"1000"
},
{
"itemNo":"Item 2",
"price":"2000"
}
}
What I’m supposed to change in code above?
Your desired output isn’t valid JSON; since you have a list of items, the outer brackets should be
[ ]. The following code generates that (Demo):Output: