使用其他元素

时间:2017-01-24 06:51:30

标签: javascript json

我有以下JSON对象

{
    "https://www.google.com": "200",
    "https://www.facebook.com": "200",
    "https://www.yahoo.com": "401",
    "https://www.friendster.com": "404"
}

是否可以在Javascript中将其转换为带有其他元素(url& status)的JSON数组?

[
  {
    "url": "https://www.google.com",
    "status": "200"
  },
  {
    "url": "https://www.facebook.com",
    "status": "200"
  },
  {
    "url": "https://www.yahoo.com",
    "status": "401"
  },
  {
    "url": "https://www.friendster.com",
    "status": "404"
  }
 ]

感谢您的提示。

2 个答案:

答案 0 :(得分:2)

使用JSON.parse解析字符串,将所有键作为数组获取,并使用url和status属性构造对象数组

var json = '{\
    "https://www.google.com": "200",\
    "https://www.facebook.com": "200",\
    "https://www.yahoo.com": "401",\
    "https://www.friendster.com": "404"\
}';
var obj = JSON.parse(json);

var objWithUrlAndStatus = Object.keys(obj).map(function (key) {
    return {
        url: key,
        status: obj[key]
    }
});

console.log(objWithUrlAndStatus);

答案 1 :(得分:1)

您可以使用jquery $ .each

像这样



var data = {
    "https://www.google.com": "200",
    "https://www.facebook.com": "200",
    "https://www.yahoo.com": "401",
    "https://www.friendster.com": "404"
};
var finalData=[];
$.each(data,function(index,val){
  finalData.push({url:index,status:val});
});

console.log(finalData);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;