从服务器返回的JSON数组:
[{"id":1,"name":"山峰类","son":[{"id":1,"name":"华山"},{"id":2,"name":"泰山"},{"id":3,"name":"黄山"}]},{"id":2,"name":"河流类","son":[{"id":7,"name":"长江"},{"id":8,"name":"黄河"}]},{"id":3,"name":"湖泊类","son":[{"id":4,"name":"洞庭湖"},{"id":5,"name":"鄱阳湖"},{"id":6,"name":"青海湖"}]}]
格式化后:
[{
"id": 1,
"name": "山峰类",
"son": [{
"id": 1,
"name": "华山"
}, {
"id": 2,
"name": "泰山"
}, {
"id": 3,
"name": "黄山"
}]
}, {
"id": 2,
"name": "河流类",
"son": [{
"id": 7,
"name": "长江"
}, {
"id": 8,
"name": "黄河"
}]
}, {
"id": 3,
"name": "湖泊类",
"son": [{
"id": 4,
"name": "洞庭湖"
}, {
"id": 5,
"name": "鄱阳湖"
}, {
"id": 6,
"name": "青海湖"
}]
}]
我想得到的数据:
[{id: 1, name: "山峰类", son: [{id: 1, name: "华山"},{id: 2, name: "泰山"}, {id: 3, name: "黄山"}]},{id: 2, name: "河流类", son: [{id: 7, name: "长江"}, {id: 8, name: "黄河"}]},{id: 3, name: "湖泊类", son: [{id: 4, name: "洞庭湖"}, {id: 5, name: "鄱阳湖"}, {id: 6, name: "青海湖"}]}]
格式化后:
[{
id: 1,
name: "山峰类",
son: [{
id: 1,
name: "华山"
}, {
id: 2,
name: "泰山"
}, {
id: 3,
name: "黄山"
}]
}, {
id: 2,
name: "河流类",
son: [{
id: 7,
name: "长江"
}, {
id: 8,
name: "黄河"
}]
}, {
id: 3,
name: "湖泊类",
son: [{
id: 4,
name: "洞庭湖"
}, {
id: 5,
name: "鄱阳湖"
}, {
id: 6,
name: "青海湖"
}]
}]
我用parse函数报错:
```javascript
var obj = JSON.parse(res.data);
/*
报错信息:
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
*/
我也曾用字符串替换函数,直接去掉KEY的双引号,也没搞定
Page({
/**
* 页面的初始数据
*/
data: {
resultTemp: [], // **请问怎么通过onload从服务器取值?**
//resultTemp: [{id: 1, name: "山峰类", son: [{id: 1, name: "华山"},{id: 2, name: "泰山"}, {id: 3, name: "黄山"}]},{id: 2, name: "河流类", son: [{id: 7, name: "长江"}, {id: 8, name: "黄河"}]},{id: 3, name: "湖泊类", son: [{id: 4, name: "洞庭湖"}, {id: 5, name: "鄱阳湖"}, {id: 6, name: "青海湖"}]}] // **这么直接初始化是没问题的**
},
onLoad: function (e) {
var that = this;
wx.request({
url: app.serverUrl + 'api/getList/',//json数据地址
headers: {
'Content-Type': 'application/json'
},
success: function (res) {
var jsonStr= res.data;
jsonStr = jsonStr.toString().replace(" ","");
if(typeof jsonStr!= 'object'){
jsonStr= jsonStr.replace(/\ufeff/g,"");
var jj = JSON.parse(jsonStr);
res.data = jj;
}
that.setData({
resultTemp: res.data,
})
}
})
卡在这个地方很多天了,反复测试一直找不到好的解决办法。
谢谢!