json_sort.html 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Sortable JSON Data</title>
  5. <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>
  6. <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  7. <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script>
  8. <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.1/themes/smoothness/jquery-ui.css">
  9. <script>
  10. function copyToClipboard(str) {
  11. var tempInput = document.createElement("input");
  12. tempInput.style = "position: absolute; left: -1000px; top: -1000px";
  13. tempInput.value = str;
  14. document.body.appendChild(tempInput);
  15. tempInput.select();
  16. document.execCommand("copy");
  17. document.body.removeChild(tempInput);
  18. }
  19. function copy() {
  20. var json = JSON.stringify(getSortedData());
  21. copyToClipboard(json);
  22. alert("success");
  23. }
  24. function getSortedData() {
  25. return $('#sortable li').map(function () {
  26. return $(this).data('item');
  27. }).toArray();
  28. }
  29. $(function () {
  30. // 初始化上传控件
  31. $('#upload').change(function () {
  32. var file = this.files[0];
  33. if (file) {
  34. var reader = new FileReader();
  35. reader.onload = function (e) {
  36. var data = JSON.parse(e.target.result);
  37. updateSortable(data);
  38. };
  39. reader.readAsText(file);
  40. }
  41. });
  42. // 初始化拖放排序控件
  43. $('#sortable').sortable({
  44. axis: 'y',
  45. stop: function (event, ui) {
  46. saveSortable();
  47. }
  48. });
  49. // 保存排序后的数据到本地
  50. function saveSortable() {
  51. var data = $('#sortable li').map(function () {
  52. return $(this).data('item');
  53. }).toArray();
  54. var json = JSON.stringify(data);
  55. var blob = new Blob([json], {type: 'application/json'});
  56. var url = URL.createObjectURL(blob);
  57. $('#download').attr('href', url);
  58. }
  59. // 更新拖放排序控件中的数据
  60. function updateSortable(data) {
  61. data.sort(function (a, b) {
  62. return (a.labels + ": " + a.name).localeCompare(b.labels + ": " + b.name);
  63. });
  64. $('#sortable').empty();
  65. $.each(data, function (i, item) {
  66. var li = $('<li>').data('item', item);
  67. $('<div>').text(item.labels + ": " + item.name).appendTo(li);
  68. $('#sortable').append(li);
  69. });
  70. saveSortable();
  71. }
  72. });
  73. </script>
  74. </head>
  75. <body>
  76. <input type="file" id="upload">
  77. <button id="copyBtn" onclick="copy()">Copy compressed JSON</button>
  78. <ul id="sortable"></ul>
  79. <a href="#" id="download" download="sorted.json">Download Sorted Data</a>
  80. </body>
  81. </html>