Home >Web Front-end >JS Tutorial >js method to convert strings in json format into objects or arrays (front and back)

js method to convert strings in json format into objects or arrays (front and back)

高洛峰
高洛峰Original
2016-12-08 10:41:421367browse

1. Frontend

// 转换成对象
 
var myObject = JSON.parse(_data);
alert("对象:"+myObject.msg);
 
 
// 转换成数组
var myobj = eval("["+_data+"]");
for (var i = 0; i < myobj.length; i++) {
alert("数组:"+myobj[i].msg);
}
 
 
//把json格式的字符串转成JSON对象
 
var json1 = &#39;{"department": "中兵","address": "北京","contacts": "李硕","telphone": "15201274666","email": "li_shilei@yeah.NET","fax": "0108596666"}&#39;;
var json2 = &#39;{"department": "中兵2","address": "北京2","contacts": "李硕2","telphone": "152012746662","email": "li_shilei2@yeah.Net","fax": "01085966662"}&#39;;
var jsonObj = $.parseJSON(json1); 或用eval方法
 
//把数组转成JSON对象
 
var arr=new Array();
arr.push(json1);
arr.push(json2);
var b=JSON.stringify(arr)

2. Backend

When you need to convert a string into a json array and traverse the contents.

Import two jar packages net.sf.json.JSONArray and net.sf.json.JSONObject on the homepage

String str = "[{name:&#39;a&#39;,value:&#39;aa&#39;},{name:&#39;b&#39;,value:&#39;bb&#39;},{name:&#39;c&#39;,value:&#39;cc&#39;},{name:&#39;d&#39;,value:&#39;dd&#39;}]" ; // 一个未转化的字符串
JSONArray json = JSONArray.fromObject(str ); // 首先把字符串转成 JSONArray 对象
if(json.size()>0){
 for(int i=0;i<json.size();i++){
  JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组,把每一个对象转成 json 对象
  System.out.println(job.get("name")+"=") ; // 得到 每个对象中的属性值
 }
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn