简体   繁体   中英

How to convert a JSON array into a JSON object in JavaScript or jQuery?

How do I convert a JSON array into a JSON object. For example, I have created a variable which holds a JSON array:

[{  "Bank Account Name": "State Bank",
    "Currency Code": "4000",
    "Deposit Date": "5/2/1794",
    "Payment Channel": "check"}]

How do I convert it into a JSON object with entities as a JSON object which look like this:

{"Entities ":[{  "Bank Account Name": "State Bank",
        "Currency Code": "4000",
        "Deposit Date": "5/2/1794",
        "Payment Channel": "check"}]
}

Is there a way to do this? I tried Stringify and parse .

 var array = [{ "Bank Account Name": "State Bank", "Currency Code": "4000", "Deposit Date": "5/2/1794", "Payment Channel": "check"}]; var obj = {"Entities" : array}; console.log(obj); 

var original  = [{  "Bank Account Name": "State Bank",
"Currency Code": "4000",
"Deposit Date": "5/2/1794",
"Payment Channel": "check"}];

var newValue = JSON.stringify({Entities:[original[0]]});

console.log(newValue);
//{"Entities":[{"Bank Account Name":"State Bank","Currency Code":"4000","Deposit Date":"5/2/1794","Payment Channel":"check"}]}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
  var obj = [{  "Bank Account Name": "State Bank",
    "Currency Code": "4000",
    "Deposit Date": "5/2/1794",
    "Payment Channel": "check"}];
var objNew={};
objNew.Entitys=obj;

alert(JSON.stringify(objNew))
});
</script>
</head>
<body>

</body>
</html>

Simply wrap it:

var array = [{  "Bank Account Name": "State Bank",
    "Currency Code": "4000",
    "Deposit Date": "5/2/1794",
    "Payment Channel": "check"}];

var jsonObject = {"Entities":array};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM