Heim > Fragen und Antworten > Hauptteil
wie
{"name":`111,password:111,title:111,tag:111,contents:1111},{"name": „222“, „password“: „22“, „title“: „22“, „tag“: „22“, „contents“: „222“}, {“name“: „11“, „password“: „11“, „title“: „11“, „tag“: „11“, „contents“: „11111“}
Konvertieren in
[{"name":`111,passwort:111,titel:111,tag:111,contents:1111},{"name" :"222", "password": "22", "title": "22", "tag": "22", "contents": "222"}, {"name": "11", "password" : „11“, „title“: „11“, „tag“: „11“, „contents“: „11111“}]
Zudem handelt es sich hierbei um die Daten, die vom Backend an das Frontend übertragen werden
仅有的幸福2017-05-19 10:13:19
// 把数据往里面一扔
var tx = {
a: {"name": "`111", "password": "111", "title": "111", "tag": "111", "contents": "1111"},
b: {"name": "222", "password": "22", "title": "22", "tag": "22", "contents": "222"},
c: {"name": "11", "password": "11", "title": "11", "tag": "11", "contents": "11111"}
};
var sb = [];
// 遍历栈入
for (var tb in tx) {
sb.push(tx[tb])
}
console.log(sb[]);
巴扎黑2017-05-19 10:13:19
完善了一下下楼上的代码,得到了楼主想要的效果
var obj = {
a: {"name": "111", "password": "111", "title": "111", "tag": "111", "contents": "1111"},
b: {"name": "222", "password": "22", "title": "22", "tag": "22", "contents": "222"},
c: {"name": "11", "password": "11", "title": "11", "tag": "11", "contents": "11111"}
};
var result = [];
for (var key in obj) {
result.push(obj[key]);
}
console.log(JSON.stringify(result));
天蓬老师2017-05-19 10:13:19
你的意思是:
将后端传来的.json文件中的数据,放到前端新的对象数组里吧。
传的话是需要ajax的(例子是jquery的ajax方法),你也可以尝试现在比较流行的axios。
假设:
1.需要传入的文件是test.json
2.test.json的数据内容是
{
"userone":{"name":"111","password":"111","title":"111","tag":"111","contents":"1111"},
"usertwo":{"name":"222","password":"22","title":"22","tag":"22","contents":"222"},
"userthree":{"name":"11","password":"11","title":"11","tag":"11","contents":"11111"}
}
转换:
1.通过ajax获取到数据,获取到的内容存在了data中
2.遍历json数据并存到新的对象数组中,在success函数中进行
function getJson(){
$.ajax({
type:"GET",
url:"test.json",
dataType:"json",
success:function(data){
var jsonData=data;
var newObject=[];
for (var key in jsonData) {
newObject.push(jsonData[key])
}
JSON.stringify(newObject);
console.log(newObject);
}
})
}
getJson();