我可以知道如何将我当前的json文件转换为嵌套的json结构,如下所示,我尝试了几种方式(How to convert form input fields to nested json structure using jquery),但我没有得到它,请帮忙我在哪里做错了,这样我们就可以使用ng-repeat在我的视图页面上迭代imageurl值。如果我使用下面的内容,则不会按照我想要的结构给出。
html:
<form id="controlid" method="post" action="" enctype="multipart/form-data" >
<input type="hidden" value="3d{{$index}}" name="3d" >
<input type="hidden" value="sliceX{{$index}}" name="sliceX">
<input type="hidden" value="sliceY{{$index}}" name="sliceY" >
<input type="hidden" value="sliceZ{{$index}}" name="sliceZ">
<input type="button" id="submitButton" value="Save">
</form>
jquery:
$("#submitButton").on('click', function(e) {
var el = document.querySelectorAll('#text [type="hidden"]');
var arr = [];
var obj = {};
var push = false;
for(var i = 0; i < el.length; i ++){
if(el[i].value.indexOf('/tests/images') > -1){
if(push){
arr.push(obj);
obj = {};
};
obj.name = 'imageurl';
obj.value = el[i].value;
push = true;
}
obj.parts = obj.parts || [];
obj.parts.push({
name: el[i].name,
value: el[i].value
});
}
var fileDataToSave = $(obj).serializeArray();
var jsoncontent = JSON.stringify( fileDataToSave );
var $downloadAnchor = $("<a/>", {
href: 'data:text/json;charset=UTF-8,' + jsoncontent,
download: "info.json"
});
$downloadAnchor.css({"position": "absolute", "left": "970px", "top":"258px"});
$downloadAnchor.text("Click here to download JSON");
$("form").append($downloadAnchor);
e.preventDefault();
return false;
});
目前的json:
[{"name":"imageurl","value":"/tests/images/Image1.nii"},{"name":"3d","value":"3d0"},{"name":"sliceX","value":"sliceX0"},{"name":"sliceY","value":"sliceY0"},{"name":"sliceZ","value":"sliceZ0"},{"name":"imageurl","value":"/tests/images/Image2.nii"},{"name":"3d","value":"3d1"},{"name":"sliceX","value":"sliceX1"},{"name":"sliceY","value":"sliceY1"},{"name":"sliceZ","value":"sliceZ1"}]`
`desired json structure:` [
{"name":"imageurl","value":"/tests/Image1.nii", parts: [
{"name":"3d","value":"3d0"},
{"name":"sliceX","value":"sliceX0"},
{"name":"sliceY","value":"sliceY0"},
{"name":"sliceZ","value":"sliceZ0"},
]},
{"name":"imageurl","value":"/tests/Image2.nii", parts: [
{"name":"3d","value":"3d1"},
{"name":"sliceX","value":"sliceX1"},
{"name":"sliceY","value":"sliceY1"},
{"name":"sliceZ","value":"sliceZ1"}
]}
]
答案 0 :(得分:1)
纯Javascript解决方案。
var json; // your current json object
var newJson = [];
for (var i = 0; i < json.length; i++) {
var node;
if (json[i].name === "imageurl") {
node = json[i];
var parts = [];
for (var j = i + 1; j < json.length; j++) {
if (json[j].name !== "imageurl") {
parts.push(json[j]);
} else {
i = j - 1;
break;
}
}
node.parts = parts;
newJson.push(node);
}
}
我们只需遍历所有元素,找到name === "imageurl"
的元素,然后将其余元素添加为部分,直到找到包含name === "imageurl"
的新元素。