index.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. /**
  2. * FeHelper Json Format Tools
  3. */
  4. // 一些全局变量
  5. let editor = {};
  6. let LOCAL_KEY_OF_LAYOUT = 'local-layout-key';
  7. let JSON_LINT = 'jsonformat:json-lint-switch';
  8. let EDIT_ON_CLICK = 'jsonformat:edit-on-click';
  9. let AUTO_DECODE = 'jsonformat:auto-decode';
  10. new Vue({
  11. el: '#pageContainer',
  12. data: {
  13. defaultResultTpl: '<div class="x-placeholder"><img src="../json-format/json-demo.jpg" alt="json-placeholder"></div>',
  14. placeHolder: '',
  15. jsonFormattedSource: '',
  16. errorMsg: '',
  17. errorJsonCode: '',
  18. errorPos: '',
  19. jfCallbackName_start: '',
  20. jfCallbackName_end: '',
  21. jsonLintSwitch: true,
  22. autoDecode: false,
  23. fireChange: true,
  24. overrideJson: false,
  25. isInUSAFlag: false,
  26. autoUnpackJsonString: false,
  27. // JSONPath查询相关
  28. jsonPathQuery: '',
  29. showJsonPathModal: false,
  30. showJsonPathExamplesModal: false,
  31. jsonPathResults: [],
  32. jsonPathError: '',
  33. copyButtonState: 'normal', // normal, copying, success, error
  34. jsonPathExamples: [
  35. { path: '$', description: '根对象' },
  36. { path: '$.data', description: '获取data属性' },
  37. { path: '$.data.*', description: '获取data下的所有属性' },
  38. { path: '$.data[0]', description: '获取data数组的第一个元素' },
  39. { path: '$.data[*]', description: '获取data数组的所有元素' },
  40. { path: '$.data[?(@.name)]', description: '获取data数组中有name属性的元素' },
  41. { path: '$..name', description: '递归查找所有name属性' },
  42. { path: '$.data[0:3]', description: '获取data数组的前3个元素' },
  43. { path: '$.data[-1]', description: '获取data数组的最后一个元素' },
  44. { path: '$.*.price', description: '获取所有子对象的price属性' }
  45. ]
  46. },
  47. mounted: function () {
  48. // 自动开关灯控制
  49. DarkModeMgr.turnLightAuto();
  50. this.placeHolder = this.defaultResultTpl;
  51. this.autoDecode = localStorage.getItem(AUTO_DECODE);
  52. this.autoDecode = this.autoDecode === 'true';
  53. this.isInUSAFlag = this.isInUSA();
  54. this.jsonLintSwitch = (localStorage.getItem(JSON_LINT) !== 'false');
  55. this.overrideJson = (localStorage.getItem(EDIT_ON_CLICK) === 'true');
  56. this.changeLayout(localStorage.getItem(LOCAL_KEY_OF_LAYOUT));
  57. editor = CodeMirror.fromTextArea(this.$refs.jsonBox, {
  58. mode: "text/javascript",
  59. lineNumbers: true,
  60. matchBrackets: true,
  61. styleActiveLine: true,
  62. lineWrapping: true
  63. });
  64. //输入框聚焦
  65. editor.focus();
  66. // 格式化以后的JSON,点击以后可以重置原内容
  67. window._OnJsonItemClickByFH = (jsonTxt) => {
  68. if (this.overrideJson) {
  69. this.disableEditorChange(jsonTxt);
  70. }
  71. };
  72. editor.on('change', (editor, changes) => {
  73. this.jsonFormattedSource = editor.getValue().replace(/\n/gm, ' ');
  74. this.fireChange && this.format();
  75. });
  76. // 在tab创建或者更新时候,监听事件,看看是否有参数传递过来
  77. if (location.protocol === 'chrome-extension:') {
  78. chrome.tabs.query({currentWindow: true,active: true, }, (tabs) => {
  79. let activeTab = tabs.filter(tab => tab.active)[0];
  80. chrome.runtime.sendMessage({
  81. type: 'fh-dynamic-any-thing',
  82. thing: 'request-page-content',
  83. tabId: activeTab.id
  84. }).then(resp => {
  85. if(!resp || !resp.content) return ;
  86. editor.setValue(resp.content || '');
  87. this.format();
  88. });
  89. });
  90. }
  91. },
  92. methods: {
  93. isInUSA: function () {
  94. // 通过时区判断是否在美国
  95. const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  96. const isUSTimeZone = /^America\/(New_York|Chicago|Denver|Los_Angeles|Anchorage|Honolulu)/.test(timeZone);
  97. // 通过语言判断
  98. const language = navigator.language || navigator.userLanguage;
  99. const isUSLanguage = language.toLowerCase().indexOf('en-us') > -1;
  100. // 如果时区和语言都符合美国特征,则认为在美国
  101. return (isUSTimeZone && isUSLanguage);
  102. },
  103. format: function () {
  104. this.errorMsg = '';
  105. this.placeHolder = this.defaultResultTpl;
  106. this.jfCallbackName_start = '';
  107. this.jfCallbackName_end = '';
  108. let source = editor.getValue().replace(/\n/gm, ' ');
  109. if (!source) {
  110. return false;
  111. }
  112. // JSONP形式下的callback name
  113. let funcName = null;
  114. // json对象
  115. let jsonObj = null;
  116. // 下面校验给定字符串是否为一个合法的json
  117. try {
  118. // 再看看是不是jsonp的格式
  119. let reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  120. let matches = reg.exec(source);
  121. if (matches != null) {
  122. funcName = matches[1];
  123. source = matches[2];
  124. }
  125. // 这里可能会throw exception
  126. jsonObj = JSON.parse(source);
  127. } catch (ex) {
  128. // new Function的方式,能自动给key补全双引号,但是不支持bigint,所以是下下策,放在try-catch里搞
  129. try {
  130. jsonObj = new Function("return " + source)();
  131. } catch (exx) {
  132. try {
  133. // 再给你一次机会,是不是下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  134. jsonObj = new Function("return '" + source + "'")();
  135. if (typeof jsonObj === 'string') {
  136. try {
  137. // 确保bigint不会失真
  138. jsonObj = JSON.parse(jsonObj);
  139. } catch (ie) {
  140. // 最后给你一次机会,是个字符串,老夫给你再转一次
  141. jsonObj = new Function("return " + jsonObj)();
  142. }
  143. }
  144. } catch (exxx) {
  145. this.errorMsg = exxx.message;
  146. }
  147. }
  148. }
  149. try{
  150. // 这里多做一个动作,给没有携带双引号的Key都自动加上,防止Long类型失真
  151. const regex = /([{,]\s*)(\w+)(\s*:)/g;
  152. source = source.replace(regex, '$1"$2"$3');
  153. jsonObj = JSON.parse(source);
  154. }catch(e){
  155. // 这里什么动作都不需要做,这种情况下转换失败的,肯定是Value被污染了,抛弃即可
  156. }
  157. // 新增:自动解包嵌套JSON字符串
  158. if (this.autoUnpackJsonString && jsonObj != null && typeof jsonObj === 'object') {
  159. jsonObj = deepParseJSONStrings(jsonObj);
  160. source = JSON.stringify(jsonObj);
  161. }
  162. // 是json格式,可以进行JSON自动格式化
  163. if (jsonObj != null && typeof jsonObj === "object" && !this.errorMsg.length) {
  164. try {
  165. let sortType = document.querySelectorAll('[name=jsonsort]:checked')[0].value;
  166. if (sortType !== '0') {
  167. jsonObj = JsonABC.sortObj(jsonObj, parseInt(sortType), true);
  168. }
  169. source = JSON.stringify(jsonObj);
  170. } catch (ex) {
  171. // 通过JSON反解不出来的,一定有问题
  172. this.errorMsg = ex.message;
  173. }
  174. if (!this.errorMsg.length) {
  175. if (this.autoDecode) {
  176. (async () => {
  177. let txt = await JsonEnDecode.urlDecodeByFetch(source);
  178. source = JsonEnDecode.uniDecode(txt);
  179. await Formatter.format(source);
  180. })();
  181. } else {
  182. (async () => {
  183. await Formatter.format(source);
  184. })();
  185. }
  186. this.placeHolder = '';
  187. this.jsonFormattedSource = source;
  188. // 如果是JSONP格式的,需要把方法名也显示出来
  189. if (funcName != null) {
  190. this.jfCallbackName_start = funcName + '(';
  191. this.jfCallbackName_end = ')';
  192. } else {
  193. this.jfCallbackName_start = '';
  194. this.jfCallbackName_end = '';
  195. }
  196. this.$nextTick(() => {
  197. this.updateWrapperHeight();
  198. })
  199. }
  200. }
  201. if (this.errorMsg.length) {
  202. if (this.jsonLintSwitch) {
  203. return this.lintOn();
  204. } else {
  205. this.placeHolder = '<span class="x-error">' + this.errorMsg + '</span>';
  206. return false;
  207. }
  208. }
  209. return true;
  210. },
  211. compress: function () {
  212. if (this.format()) {
  213. let jsonTxt = this.jfCallbackName_start + this.jsonFormattedSource + this.jfCallbackName_end;
  214. this.disableEditorChange(jsonTxt);
  215. }
  216. },
  217. autoDecodeFn: function () {
  218. this.$nextTick(() => {
  219. localStorage.setItem(AUTO_DECODE, this.autoDecode);
  220. this.format();
  221. });
  222. },
  223. uniEncode: function () {
  224. editor.setValue(JsonEnDecode.uniEncode(editor.getValue()));
  225. },
  226. uniDecode: function () {
  227. editor.setValue(JsonEnDecode.uniDecode(editor.getValue()));
  228. },
  229. urlDecode: function () {
  230. JsonEnDecode.urlDecodeByFetch(editor.getValue()).then(text => editor.setValue(text));
  231. },
  232. updateWrapperHeight: function () {
  233. let curLayout = localStorage.getItem(LOCAL_KEY_OF_LAYOUT);
  234. let elPc = document.querySelector('#pageContainer');
  235. if (curLayout === 'up-down') {
  236. elPc.style.height = 'auto';
  237. } else {
  238. elPc.style.height = Math.max(elPc.scrollHeight, document.body.scrollHeight) + 'px';
  239. }
  240. },
  241. changeLayout: function (type) {
  242. let elPc = document.querySelector('#pageContainer');
  243. if (type === 'up-down') {
  244. elPc.classList.remove('layout-left-right');
  245. elPc.classList.add('layout-up-down');
  246. this.$refs.btnLeftRight.classList.remove('selected');
  247. this.$refs.btnUpDown.classList.add('selected');
  248. } else {
  249. elPc.classList.remove('layout-up-down');
  250. elPc.classList.add('layout-left-right');
  251. this.$refs.btnLeftRight.classList.add('selected');
  252. this.$refs.btnUpDown.classList.remove('selected');
  253. }
  254. localStorage.setItem(LOCAL_KEY_OF_LAYOUT, type);
  255. this.updateWrapperHeight();
  256. },
  257. setCache: function () {
  258. this.$nextTick(() => {
  259. localStorage.setItem(EDIT_ON_CLICK, this.overrideJson);
  260. });
  261. },
  262. lintOn: function () {
  263. this.$nextTick(() => {
  264. localStorage.setItem(JSON_LINT, this.jsonLintSwitch);
  265. });
  266. if (!editor.getValue().trim()) {
  267. return true;
  268. }
  269. this.$nextTick(() => {
  270. if (!this.jsonLintSwitch) {
  271. return;
  272. }
  273. let lintResult = JsonLint.lintDetect(editor.getValue());
  274. if (!isNaN(lintResult.line)) {
  275. this.placeHolder = '<div id="errorTips">' +
  276. '<div id="tipsBox">错误位置:' + (lintResult.line + 1) + '行,' + (lintResult.col + 1) + '列;缺少字符或字符不正确</div>' +
  277. '<div id="errorCode">' + lintResult.dom + '</div></div>';
  278. }
  279. });
  280. return false;
  281. },
  282. disableEditorChange: function (jsonTxt) {
  283. this.fireChange = false;
  284. this.$nextTick(() => {
  285. editor.setValue(jsonTxt);
  286. this.$nextTick(() => {
  287. this.fireChange = true;
  288. })
  289. })
  290. },
  291. openOptionsPage: function(event){
  292. event.preventDefault();
  293. event.stopPropagation();
  294. chrome.runtime.openOptionsPage();
  295. },
  296. openDonateModal: function(event){
  297. event.preventDefault();
  298. event.stopPropagation();
  299. chrome.runtime.sendMessage({
  300. type: 'fh-dynamic-any-thing',
  301. thing: 'open-donate-modal',
  302. params: { toolName: 'json-format' }
  303. });
  304. },
  305. setDemo: function () {
  306. let demo = '{"BigIntSupported":995815895020119788889,"date":"20180322","url":"https://www.baidu.com?wd=fehelper","img":"http://gips0.baidu.com/it/u=1490237218,4115737545&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=720","message":"Success !","status":200,"city":"北京","count":632,"data":{"shidu":"34%","pm25":73,"pm10":91,"quality":"良","wendu":"5","ganmao":"极少数敏感人群应减少户外活动","yesterday":{"date":"21日星期三","sunrise":"06:19","high":"高温 11.0℃","low":"低温 1.0℃","sunset":"18:26","aqi":85,"fx":"南风","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"},"forecast":[{"date":"22日星期四","sunrise":"06:17","high":"高温 17.0℃","low":"低温 1.0℃","sunset":"18:27","aqi":98,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"23日星期五","sunrise":"06:16","high":"高温 18.0℃","low":"低温 5.0℃","sunset":"18:28","aqi":118,"fx":"无持续风向","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"},{"date":"24日星期六","sunrise":"06:14","high":"高温 21.0℃","low":"低温 7.0℃","sunset":"18:29","aqi":52,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"25日星期日","sunrise":"06:13","high":"高温 22.0℃","low":"低温 7.0℃","sunset":"18:30","aqi":71,"fx":"西南风","fl":"<3级","type":"晴","notice":"愿你拥有比阳光明媚的心情"},{"date":"26日星期一","sunrise":"06:11","high":"高温 21.0℃","low":"低温 8.0℃","sunset":"18:31","aqi":97,"fx":"西南风","fl":"<3级","type":"多云","notice":"阴晴之间,谨防紫外线侵扰"}]}}';
  307. editor.setValue(demo);
  308. this.$nextTick(() => {
  309. this.format();
  310. })
  311. },
  312. autoUnpackJsonStringFn: function () {
  313. this.$nextTick(() => {
  314. localStorage.setItem('jsonformat:auto-unpack-json-string', this.autoUnpackJsonString);
  315. this.format();
  316. });
  317. },
  318. // JSONPath查询功能
  319. executeJsonPath: function() {
  320. this.jsonPathError = '';
  321. this.jsonPathResults = [];
  322. if (!this.jsonPathQuery.trim()) {
  323. this.jsonPathError = '请输入JSONPath查询表达式';
  324. return;
  325. }
  326. let source = this.jsonFormattedSource || editor.getValue();
  327. if (!source.trim()) {
  328. this.jsonPathError = '请先输入JSON数据';
  329. return;
  330. }
  331. try {
  332. let jsonObj = JSON.parse(source);
  333. this.jsonPathResults = this.queryJsonPath(jsonObj, this.jsonPathQuery.trim());
  334. this.showJsonPathModal = true;
  335. } catch (error) {
  336. this.jsonPathError = 'JSON格式错误:' + error.message;
  337. this.showJsonPathModal = true;
  338. }
  339. },
  340. // JSONPath查询引擎
  341. queryJsonPath: function(obj, path) {
  342. let results = [];
  343. try {
  344. // 简化的JSONPath解析器
  345. if (path === '$') {
  346. results.push({ path: '$', value: obj });
  347. return results;
  348. }
  349. // 移除开头的$
  350. if (path.startsWith('$.')) {
  351. path = path.substring(2);
  352. } else if (path.startsWith('$')) {
  353. path = path.substring(1);
  354. }
  355. // 执行查询
  356. this.evaluateJsonPath(obj, path, '$', results);
  357. } catch (error) {
  358. throw new Error('JSONPath表达式错误:' + error.message);
  359. }
  360. return results;
  361. },
  362. // 递归评估JSONPath
  363. evaluateJsonPath: function(current, path, currentPath, results) {
  364. if (!path) {
  365. results.push({ path: currentPath, value: current });
  366. return;
  367. }
  368. // 处理递归搜索 ..
  369. if (path.startsWith('..')) {
  370. let remainPath = path.substring(2);
  371. this.recursiveSearch(current, remainPath, currentPath, results);
  372. return;
  373. }
  374. // 解析下一个路径片段
  375. let match;
  376. // 处理数组索引 [index] 或 [*] 或 [start:end]
  377. if ((match = path.match(/^\[([^\]]+)\](.*)$/))) {
  378. let indexExpr = match[1];
  379. let remainPath = match[2];
  380. if (!Array.isArray(current)) {
  381. return;
  382. }
  383. if (indexExpr === '*') {
  384. // 通配符:所有元素
  385. current.forEach((item, index) => {
  386. this.evaluateJsonPath(item, remainPath, currentPath + '[' + index + ']', results);
  387. });
  388. } else if (indexExpr.includes(':')) {
  389. // 数组切片 [start:end]
  390. let [start, end] = indexExpr.split(':').map(s => s.trim() === '' ? undefined : parseInt(s));
  391. let sliced = current.slice(start, end);
  392. sliced.forEach((item, index) => {
  393. let actualIndex = (start || 0) + index;
  394. this.evaluateJsonPath(item, remainPath, currentPath + '[' + actualIndex + ']', results);
  395. });
  396. } else if (indexExpr.startsWith('?(')) {
  397. // 过滤表达式 [?(@.prop)]
  398. current.forEach((item, index) => {
  399. if (this.evaluateFilter(item, indexExpr)) {
  400. this.evaluateJsonPath(item, remainPath, currentPath + '[' + index + ']', results);
  401. }
  402. });
  403. } else {
  404. // 具体索引
  405. let index = parseInt(indexExpr);
  406. if (index < 0) {
  407. index = current.length + index; // 负索引
  408. }
  409. if (index >= 0 && index < current.length) {
  410. this.evaluateJsonPath(current[index], remainPath, currentPath + '[' + index + ']', results);
  411. }
  412. }
  413. return;
  414. }
  415. // 处理属性访问 .property 或直接属性名
  416. if ((match = path.match(/^\.?([^.\[]+)(.*)$/))) {
  417. let prop = match[1];
  418. let remainPath = match[2];
  419. if (prop === '*') {
  420. // 通配符:所有属性
  421. if (typeof current === 'object' && current !== null) {
  422. Object.keys(current).forEach(key => {
  423. this.evaluateJsonPath(current[key], remainPath, currentPath + '.' + key, results);
  424. });
  425. }
  426. } else {
  427. // 具体属性
  428. if (typeof current === 'object' && current !== null && current.hasOwnProperty(prop)) {
  429. this.evaluateJsonPath(current[prop], remainPath, currentPath + '.' + prop, results);
  430. }
  431. }
  432. return;
  433. }
  434. // 处理方括号属性访问 ['property']
  435. if ((match = path.match(/^\['([^']+)'\](.*)$/))) {
  436. let prop = match[1];
  437. let remainPath = match[2];
  438. if (typeof current === 'object' && current !== null && current.hasOwnProperty(prop)) {
  439. this.evaluateJsonPath(current[prop], remainPath, currentPath + "['" + prop + "']", results);
  440. }
  441. return;
  442. }
  443. // 如果没有特殊符号,当作属性名处理
  444. if (typeof current === 'object' && current !== null && current.hasOwnProperty(path)) {
  445. results.push({ path: currentPath + '.' + path, value: current[path] });
  446. }
  447. },
  448. // 递归搜索
  449. recursiveSearch: function(current, targetProp, currentPath, results) {
  450. if (typeof current === 'object' && current !== null) {
  451. // 检查当前对象的属性
  452. if (current.hasOwnProperty(targetProp)) {
  453. results.push({ path: currentPath + '..' + targetProp, value: current[targetProp] });
  454. }
  455. // 递归搜索子对象
  456. Object.keys(current).forEach(key => {
  457. if (Array.isArray(current[key])) {
  458. current[key].forEach((item, index) => {
  459. this.recursiveSearch(item, targetProp, currentPath + '.' + key + '[' + index + ']', results);
  460. });
  461. } else if (typeof current[key] === 'object' && current[key] !== null) {
  462. this.recursiveSearch(current[key], targetProp, currentPath + '.' + key, results);
  463. }
  464. });
  465. }
  466. },
  467. // 简单的过滤器评估
  468. evaluateFilter: function(item, filterExpr) {
  469. // 简化的过滤器实现,只支持基本的属性存在性检查
  470. // 如 ?(@.name) 检查是否有name属性
  471. let match = filterExpr.match(/^\?\(@\.(\w+)\)$/);
  472. if (match) {
  473. let prop = match[1];
  474. return typeof item === 'object' && item !== null && item.hasOwnProperty(prop);
  475. }
  476. // 支持简单的比较 ?(@.age > 18)
  477. match = filterExpr.match(/^\?\(@\.(\w+)\s*([><=!]+)\s*(.+)\)$/);
  478. if (match) {
  479. let prop = match[1];
  480. let operator = match[2];
  481. let value = match[3];
  482. if (typeof item === 'object' && item !== null && item.hasOwnProperty(prop)) {
  483. let itemValue = item[prop];
  484. let compareValue = isNaN(value) ? value.replace(/['"]/g, '') : parseFloat(value);
  485. switch (operator) {
  486. case '>': return itemValue > compareValue;
  487. case '<': return itemValue < compareValue;
  488. case '>=': return itemValue >= compareValue;
  489. case '<=': return itemValue <= compareValue;
  490. case '==': return itemValue == compareValue;
  491. case '!=': return itemValue != compareValue;
  492. }
  493. }
  494. }
  495. return false;
  496. },
  497. // 显示JSONPath示例
  498. showJsonPathExamples: function() {
  499. this.showJsonPathExamplesModal = true;
  500. },
  501. // 使用JSONPath示例
  502. useJsonPathExample: function(path) {
  503. this.jsonPathQuery = path;
  504. this.closeJsonPathExamplesModal();
  505. },
  506. // 打开JSONPath查询模态框
  507. openJsonPathModal: function() {
  508. this.showJsonPathModal = true;
  509. // 清空之前的查询结果
  510. this.jsonPathResults = [];
  511. this.jsonPathError = '';
  512. this.copyButtonState = 'normal';
  513. },
  514. // 关闭JSONPath结果模态框
  515. closeJsonPathModal: function() {
  516. this.showJsonPathModal = false;
  517. this.copyButtonState = 'normal'; // 重置复制按钮状态
  518. },
  519. // 关闭JSONPath示例模态框
  520. closeJsonPathExamplesModal: function() {
  521. this.showJsonPathExamplesModal = false;
  522. },
  523. // 格式化JSONPath查询结果
  524. formatJsonPathResult: function(value) {
  525. if (typeof value === 'object') {
  526. return JSON.stringify(value, null, 2);
  527. }
  528. return String(value);
  529. },
  530. // 复制JSONPath查询结果
  531. copyJsonPathResults: function() {
  532. let resultText = this.jsonPathResults.map(result => {
  533. return `路径: ${result.path}\n值: ${this.formatJsonPathResult(result.value)}`;
  534. }).join('\n\n');
  535. // 设置复制状态
  536. this.copyButtonState = 'copying';
  537. navigator.clipboard.writeText(resultText).then(() => {
  538. this.copyButtonState = 'success';
  539. setTimeout(() => {
  540. this.copyButtonState = 'normal';
  541. }, 2000);
  542. }).catch(() => {
  543. // 兼容旧浏览器
  544. try {
  545. let textArea = document.createElement('textarea');
  546. textArea.value = resultText;
  547. document.body.appendChild(textArea);
  548. textArea.select();
  549. document.execCommand('copy');
  550. document.body.removeChild(textArea);
  551. this.copyButtonState = 'success';
  552. setTimeout(() => {
  553. this.copyButtonState = 'normal';
  554. }, 2000);
  555. } catch (error) {
  556. this.copyButtonState = 'error';
  557. setTimeout(() => {
  558. this.copyButtonState = 'normal';
  559. }, 2000);
  560. }
  561. });
  562. },
  563. // 下载JSONPath查询结果
  564. downloadJsonPathResults: function() {
  565. let resultText = this.jsonPathResults.map(result => {
  566. return `路径: ${result.path}\n值: ${this.formatJsonPathResult(result.value)}`;
  567. }).join('\n\n');
  568. // 基于JSONPath生成文件名
  569. let filename = this.generateFilenameFromPath(this.jsonPathQuery);
  570. let blob = new Blob([resultText], { type: 'text/plain;charset=utf-8' });
  571. let url = window.URL.createObjectURL(blob);
  572. let a = document.createElement('a');
  573. a.href = url;
  574. a.download = filename + '.txt';
  575. document.body.appendChild(a);
  576. a.click();
  577. document.body.removeChild(a);
  578. window.URL.revokeObjectURL(url);
  579. },
  580. // 根据JSONPath生成文件名
  581. generateFilenameFromPath: function(path) {
  582. if (!path || path === '$') {
  583. return 'jsonpath_root';
  584. }
  585. // 移除开头的$和.
  586. let cleanPath = path.replace(/^\$\.?/, '');
  587. // 替换特殊字符为下划线,保留数字、字母、点号、中划线
  588. let filename = cleanPath
  589. .replace(/[\[\]]/g, '_') // 方括号替换为下划线
  590. .replace(/[^\w\u4e00-\u9fa5.-]/g, '_') // 特殊字符替换为下划线,保留中文
  591. .replace(/_{2,}/g, '_') // 多个连续下划线合并为一个
  592. .replace(/^_|_$/g, ''); // 移除开头和结尾的下划线
  593. // 如果处理后为空,使用默认名称
  594. if (!filename) {
  595. return 'jsonpath_query';
  596. }
  597. // 限制文件名长度
  598. if (filename.length > 50) {
  599. filename = filename.substring(0, 50) + '_truncated';
  600. }
  601. return 'jsonpath_' + filename;
  602. }
  603. }
  604. });
  605. // 新增:递归解包嵌套JSON字符串的函数
  606. function deepParseJSONStrings(obj) {
  607. if (Array.isArray(obj)) {
  608. return obj.map(deepParseJSONStrings);
  609. } else if (typeof obj === 'object' && obj !== null) {
  610. const newObj = {};
  611. for (const key in obj) {
  612. if (!obj.hasOwnProperty(key)) continue;
  613. const val = obj[key];
  614. if (typeof val === 'string') {
  615. try {
  616. const parsed = JSON.parse(val);
  617. // 只递归对象或数组
  618. if (typeof parsed === 'object' && parsed !== null) {
  619. newObj[key] = deepParseJSONStrings(parsed);
  620. continue;
  621. }
  622. } catch (e) {}
  623. }
  624. newObj[key] = deepParseJSONStrings(val);
  625. }
  626. return newObj;
  627. }
  628. return obj;
  629. }