格式化JSON对象并向结构添加新键

时间:2015-02-04 13:36:29

标签: javascript json

我是JSON的新手,想要一些输入。我有一个地址的JSON对象,如下所示。在同一个键中有多个地址由||分隔。

原始JSON是:{"地址":" 123死驱,露营山,PA || 456 N Street,Harrisburg,PA"};

我正在尝试重新格式化此JSON以使用逗号分隔2个不同的地址,如下所示。

{"Address":
       "Formatted Address" : 
               "Street Address":"123 dead drive"
               "City": "camp hill"
               "State": "PA" ,
       "Formatted Address" : 
               "Street Address":"456 N Street"
               "City": "Harrisburg"
               "State": "PA"
}

我正在尝试这样的事情

$(function() {
   var resultJSON = '{"Address":"123 dead drive,camp hill,PA || 456 N Street,Harrisburg, PA"}';
var result = $.parseJSON(resultJSON);

var splitresult = result.Address.split("||");   
  address = [];  

  $(splitresult).each(function(index) {
      address.push({'Formatted': splitresult[index]});   
    });

  var json0bj =  JSON.stringify(address);
    console.log(json0bj);   
});

1 个答案:

答案 0 :(得分:1)

编辑:注释代码以显示已完成的操作。 对您的代码进行了一些小改动:

$(function() {
  var resultJSON = '{"Address":"123 dead drive,camp hill,PA || 456 N Street,Harrisburg, PA"}';
  var result = $.parseJSON(resultJSON);

  var splitresult = result.Address.split(" || ");
  address = [];

  $(splitresult).each(function(index, element) {
    // $.each passes the element as the second argument. We'll use that.
    var adrArray = element.split(',');
    // We split the string on commas to get the address fragments and place them  into a new object:
    var formattedAddress = {
      "Street Address": adrArray[0],
      "City": adrArray[1],
      "State": adrArray[2]
    };
    // Then push it onto the array:
    address.push({
      'Formatted Adress': formattedAddress
    });
  });

  //To make the result look like the one you want we put the array into a new structure:
  var addressObject = {
    "Address": address
  };
  var jsonObj = JSON.stringify(addressObject);
  document.write("<code>"+jsonObj+"</code>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>