私が扱っている状況は、JSON オブジェクト (JavaScript オブジェクトとして表される) からデータを取得してデータの一部を抽出し、そのデータを使用して JavaScript を使用して新しいオブジェクトを生成することです。新しいオブジェクトも、新しく追加されたデータで構成されます。
次のオブジェクトがあるとします。
sprite_set = {
"frames": {
"grass.png": {
"frame": {
"x": 1766,
"y": 202
},
"rotated": false,
"sourceSize": {
"w": 128,
"h": 128
}
},
"dirt1.png": {
"frame": {
"x": 1766,
"y": 202
},
"rotated": false,
"sourceSize": {
"w": 128,
"h": 128
}
},
"dirt2.png": {
"frame": {
"x": 2766,
"y": 402
},
"rotated": false,
"sourceSize": {
"w": 128,
"h": 128
}
}
}
};
このオブジェクトから、次の新しいオブジェクトを作成したいと思います。
sprite_set = {
"frames": {
"grass": {
"frame": {
"x": 1766,
"y": 202
},
"sourceSize": {
"w": 128,
"h": 128
}
},
"dirt": {
"multi_frames": {
"frame1": {
"x": 1766,
"y": 202
},
"frame2": {
"x": 2766,
"y": 402
}
},
"sourceSize": {
"w": 128,
"h": 128
}
}
}
};
したがって、次のルールを使用して、生のオブジェクトを取得し、新しいオブジェクトを吐き出す関数を作成する必要があります。
- 各「フレーム」からすべての「回転」プロパティを削除します
- 「frames」の各サブオブジェクトの名前を変更して.pngを削除し、「grass.png」が「grass」に変更されるようにします
- 「フレーム」サブオブジェクト名に先頭の番号が含まれていない場合は、そのまま新しいオブジェクトに配置します。
- 「frames」サブオブジェクト名に先頭の数字が含まれている場合、後続の各数字を、親が「multi_frames」である新しいサブオブジェクトに分割します。
私は本当にJSONにまったく慣れていないので、これをどのように開始するかについての助けは素晴らしいでしょう. 私は学びたくないので、助けがあればこの問題に取り組み、この回答の最後で私がどのようにそれを行っているかを常に更新します。
もう 1 つの質問ですが、このプロセスをはるかに簡単にする JavaScript ライブラリはありますか?
誰の助けにも感謝します。
アップデート
人々のコメントからの助けから、これは私がこれまでに持っていることです:
HTML
<input type="file" id="files" name="files[]" />
* JavaScript *
var JsonObj = null;
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
f = files[0];
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
JsonObj = e.target.result
console.log(JsonObj);
var parsedJSON = JSON.parse(JsonObj);
var oldframes = parsedJSON.frames,
newframes = {};
for (var framename in oldframes) {
// var m = framename.match(/(.*)\.[^.]+$/);
var m = framename.match(/^(.+?)(\d*)\.png$/);
var newname = m[1];
var frame = oldframes[framename];
if (newname in newframes) newframes[newname].multi_frames["frame" + m[2]] = frame.frame;
else newframes[newname] = {
frame: frame.frame,
sourcesize: frame.sourcsize
};
// or, if it's OK to mutate the old objects, just:
// delete frame.rotated;
// newframes[newname] = frame;
}
parsedJSON.frames = newframes;
JsonObj = JSON.stringify(parsedJSON, null, 4)
console.log(JsonObj);
};
})(f);
// Read in JSON as a data URL.
reader.readAsText(f, 'UTF-8');
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
HTML5 File Api を使用して JSON ファイルを取得します。次のエラーが表示されます
Uncaught TypeError: Cannot set property 'frame2' of undefined fiddle >
(anonymous function)
行を参照して:
if (newname in newframes) newframes[newname].multi_frames["frame" + m[2]] = frame.frame;
問題が何であるかわかりません。アイデアはありますか?
ここにライブ JSFiddle があります。http://jsfiddle.net/jamiefearon/8kUYj/48/
現在修正済み: ここでフィドル: http://jsfiddle.net/jamiefearon/8kUYj/50/