index.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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. // 页面加载时自动获取并注入json-format页面的补丁
  92. this.loadPatchHotfix();
  93. },
  94. methods: {
  95. loadPatchHotfix() {
  96. // 页面加载时自动获取并注入页面的补丁
  97. chrome.runtime.sendMessage({
  98. type: 'fh-dynamic-any-thing',
  99. thing: 'fh-get-tool-patch',
  100. toolName: 'json-format'
  101. }, patch => {
  102. if (patch) {
  103. if (patch.css) {
  104. const style = document.createElement('style');
  105. style.textContent = patch.css;
  106. document.head.appendChild(style);
  107. }
  108. if (patch.js) {
  109. try {
  110. if (window.evalCore && window.evalCore.getEvalInstance) {
  111. window.evalCore.getEvalInstance(window)(patch.js);
  112. }
  113. } catch (e) {
  114. console.error('json-format补丁JS执行失败', e);
  115. }
  116. }
  117. }
  118. });
  119. },
  120. isInUSA: function () {
  121. // 通过时区判断是否在美国
  122. const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  123. const isUSTimeZone = /^America\/(New_York|Chicago|Denver|Los_Angeles|Anchorage|Honolulu)/.test(timeZone);
  124. // 通过语言判断
  125. const language = navigator.language || navigator.userLanguage;
  126. const isUSLanguage = language.toLowerCase().indexOf('en-us') > -1;
  127. // 如果时区和语言都符合美国特征,则认为在美国
  128. return (isUSTimeZone && isUSLanguage);
  129. },
  130. format: function () {
  131. this.errorMsg = '';
  132. this.placeHolder = this.defaultResultTpl;
  133. this.jfCallbackName_start = '';
  134. this.jfCallbackName_end = '';
  135. let source = editor.getValue().replace(/\n/gm, ' ');
  136. if (!source) {
  137. return false;
  138. }
  139. // JSONP形式下的callback name
  140. let funcName = null;
  141. // json对象
  142. let jsonObj = null;
  143. // 下面校验给定字符串是否为一个合法的json
  144. try {
  145. // 再看看是不是jsonp的格式
  146. let reg = /^([\w\.]+)\(\s*([\s\S]*)\s*\)$/igm;
  147. let matches = reg.exec(source);
  148. if (matches != null) {
  149. funcName = matches[1];
  150. source = matches[2];
  151. }
  152. // 这里可能会throw exception
  153. jsonObj = JSON.parse(source);
  154. } catch (ex) {
  155. // new Function的方式,能自动给key补全双引号,但是不支持bigint,所以是下下策,放在try-catch里搞
  156. try {
  157. jsonObj = new Function("return " + source)();
  158. } catch (exx) {
  159. try {
  160. // 再给你一次机会,是不是下面这种情况: "{\"ret\":\"0\", \"msg\":\"ok\"}"
  161. jsonObj = new Function("return '" + source + "'")();
  162. if (typeof jsonObj === 'string') {
  163. try {
  164. // 确保bigint不会失真
  165. jsonObj = JSON.parse(jsonObj);
  166. } catch (ie) {
  167. // 最后给你一次机会,是个字符串,老夫给你再转一次
  168. jsonObj = new Function("return " + jsonObj)();
  169. }
  170. }
  171. } catch (exxx) {
  172. this.errorMsg = exxx.message;
  173. }
  174. }
  175. }
  176. try{
  177. // 这里多做一个动作,给没有携带双引号的Key都自动加上,防止Long类型失真
  178. const regex = /([{,]\s*)(\w+)(\s*:)/g;
  179. source = source.replace(regex, '$1"$2"$3');
  180. jsonObj = JSON.parse(source);
  181. }catch(e){
  182. // 这里什么动作都不需要做,这种情况下转换失败的,肯定是Value被污染了,抛弃即可
  183. }
  184. // 新增:自动解包嵌套JSON字符串
  185. if (this.autoUnpackJsonString && jsonObj != null && typeof jsonObj === 'object') {
  186. jsonObj = deepParseJSONStrings(jsonObj);
  187. source = JSON.stringify(jsonObj);
  188. }
  189. // 是json格式,可以进行JSON自动格式化
  190. if (jsonObj != null && typeof jsonObj === "object" && !this.errorMsg.length) {
  191. try {
  192. let sortType = document.querySelectorAll('[name=jsonsort]:checked')[0].value;
  193. if (sortType !== '0') {
  194. jsonObj = JsonABC.sortObj(jsonObj, parseInt(sortType), true);
  195. }
  196. source = JSON.stringify(jsonObj);
  197. } catch (ex) {
  198. // 通过JSON反解不出来的,一定有问题
  199. this.errorMsg = ex.message;
  200. }
  201. if (!this.errorMsg.length) {
  202. if (this.autoDecode) {
  203. (async () => {
  204. let txt = await JsonEnDecode.urlDecodeByFetch(source);
  205. source = JsonEnDecode.uniDecode(txt);
  206. await Formatter.format(source);
  207. })();
  208. } else {
  209. (async () => {
  210. await Formatter.format(source);
  211. })();
  212. }
  213. this.placeHolder = '';
  214. this.jsonFormattedSource = source;
  215. // 如果是JSONP格式的,需要把方法名也显示出来
  216. if (funcName != null) {
  217. this.jfCallbackName_start = funcName + '(';
  218. this.jfCallbackName_end = ')';
  219. } else {
  220. this.jfCallbackName_start = '';
  221. this.jfCallbackName_end = '';
  222. }
  223. this.$nextTick(() => {
  224. this.updateWrapperHeight();
  225. })
  226. }
  227. }
  228. if (this.errorMsg.length) {
  229. if (this.jsonLintSwitch) {
  230. return this.lintOn();
  231. } else {
  232. this.placeHolder = '<span class="x-error">' + this.errorMsg + '</span>';
  233. return false;
  234. }
  235. }
  236. return true;
  237. },
  238. compress: function () {
  239. if (this.format()) {
  240. let jsonTxt = this.jfCallbackName_start + this.jsonFormattedSource + this.jfCallbackName_end;
  241. this.disableEditorChange(jsonTxt);
  242. }
  243. },
  244. autoDecodeFn: function () {
  245. this.$nextTick(() => {
  246. localStorage.setItem(AUTO_DECODE, this.autoDecode);
  247. this.format();
  248. });
  249. },
  250. uniEncode: function () {
  251. editor.setValue(JsonEnDecode.uniEncode(editor.getValue()));
  252. },
  253. uniDecode: function () {
  254. editor.setValue(JsonEnDecode.uniDecode(editor.getValue()));
  255. },
  256. urlDecode: function () {
  257. JsonEnDecode.urlDecodeByFetch(editor.getValue()).then(text => editor.setValue(text));
  258. },
  259. updateWrapperHeight: function () {
  260. let curLayout = localStorage.getItem(LOCAL_KEY_OF_LAYOUT);
  261. let elPc = document.querySelector('#pageContainer');
  262. if (curLayout === 'up-down') {
  263. elPc.style.height = 'auto';
  264. } else {
  265. elPc.style.height = Math.max(elPc.scrollHeight, document.body.scrollHeight) + 'px';
  266. }
  267. },
  268. changeLayout: function (type) {
  269. let elPc = document.querySelector('#pageContainer');
  270. if (type === 'up-down') {
  271. elPc.classList.remove('layout-left-right');
  272. elPc.classList.add('layout-up-down');
  273. this.$refs.btnLeftRight.classList.remove('selected');
  274. this.$refs.btnUpDown.classList.add('selected');
  275. } else {
  276. elPc.classList.remove('layout-up-down');
  277. elPc.classList.add('layout-left-right');
  278. this.$refs.btnLeftRight.classList.add('selected');
  279. this.$refs.btnUpDown.classList.remove('selected');
  280. }
  281. localStorage.setItem(LOCAL_KEY_OF_LAYOUT, type);
  282. this.updateWrapperHeight();
  283. },
  284. setCache: function () {
  285. this.$nextTick(() => {
  286. localStorage.setItem(EDIT_ON_CLICK, this.overrideJson);
  287. });
  288. },
  289. lintOn: function () {
  290. this.$nextTick(() => {
  291. localStorage.setItem(JSON_LINT, this.jsonLintSwitch);
  292. });
  293. if (!editor.getValue().trim()) {
  294. return true;
  295. }
  296. this.$nextTick(() => {
  297. if (!this.jsonLintSwitch) {
  298. return;
  299. }
  300. let lintResult = JsonLint.lintDetect(editor.getValue());
  301. if (!isNaN(lintResult.line)) {
  302. this.placeHolder = '<div id="errorTips">' +
  303. '<div id="tipsBox">错误位置:' + (lintResult.line + 1) + '行,' + (lintResult.col + 1) + '列;缺少字符或字符不正确</div>' +
  304. '<div id="errorCode">' + lintResult.dom + '</div></div>';
  305. }
  306. });
  307. return false;
  308. },
  309. disableEditorChange: function (jsonTxt) {
  310. this.fireChange = false;
  311. this.$nextTick(() => {
  312. editor.setValue(jsonTxt);
  313. this.$nextTick(() => {
  314. this.fireChange = true;
  315. })
  316. })
  317. },
  318. openOptionsPage: function(event){
  319. event.preventDefault();
  320. event.stopPropagation();
  321. chrome.runtime.openOptionsPage();
  322. },
  323. openDonateModal: function(event){
  324. event.preventDefault();
  325. event.stopPropagation();
  326. chrome.runtime.sendMessage({
  327. type: 'fh-dynamic-any-thing',
  328. thing: 'open-donate-modal',
  329. params: { toolName: 'json-format' }
  330. });
  331. },
  332. setDemo: function () {
  333. 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":"阴晴之间,谨防紫外线侵扰"}]}}';
  334. editor.setValue(demo);
  335. this.$nextTick(() => {
  336. this.format();
  337. })
  338. },
  339. autoUnpackJsonStringFn: function () {
  340. this.$nextTick(() => {
  341. localStorage.setItem('jsonformat:auto-unpack-json-string', this.autoUnpackJsonString);
  342. this.format();
  343. });
  344. },
  345. // JSONPath查询功能
  346. executeJsonPath: function() {
  347. this.jsonPathError = '';
  348. this.jsonPathResults = [];
  349. if (!this.jsonPathQuery.trim()) {
  350. this.jsonPathError = '请输入JSONPath查询表达式';
  351. return;
  352. }
  353. let source = this.jsonFormattedSource || editor.getValue();
  354. if (!source.trim()) {
  355. this.jsonPathError = '请先输入JSON数据';
  356. return;
  357. }
  358. try {
  359. let jsonObj = JSON.parse(source);
  360. this.jsonPathResults = this.queryJsonPath(jsonObj, this.jsonPathQuery.trim());
  361. this.showJsonPathModal = true;
  362. } catch (error) {
  363. this.jsonPathError = 'JSON格式错误:' + error.message;
  364. this.showJsonPathModal = true;
  365. }
  366. },
  367. // JSONPath查询引擎
  368. queryJsonPath: function(obj, path) {
  369. let results = [];
  370. try {
  371. // 简化的JSONPath解析器
  372. if (path === '$') {
  373. results.push({ path: '$', value: obj });
  374. return results;
  375. }
  376. // 移除开头的$
  377. if (path.startsWith('$.')) {
  378. path = path.substring(2);
  379. } else if (path.startsWith('$')) {
  380. path = path.substring(1);
  381. }
  382. // 执行查询
  383. this.evaluateJsonPath(obj, path, '$', results);
  384. } catch (error) {
  385. throw new Error('JSONPath表达式错误:' + error.message);
  386. }
  387. return results;
  388. },
  389. // 递归评估JSONPath
  390. evaluateJsonPath: function(current, path, currentPath, results) {
  391. if (!path) {
  392. results.push({ path: currentPath, value: current });
  393. return;
  394. }
  395. // 处理递归搜索 ..
  396. if (path.startsWith('..')) {
  397. let remainPath = path.substring(2);
  398. this.recursiveSearch(current, remainPath, currentPath, results);
  399. return;
  400. }
  401. // 解析下一个路径片段
  402. let match;
  403. // 处理数组索引 [index] 或 [*] 或 [start:end]
  404. if ((match = path.match(/^\[([^\]]+)\](.*)$/))) {
  405. let indexExpr = match[1];
  406. let remainPath = match[2];
  407. if (!Array.isArray(current)) {
  408. return;
  409. }
  410. if (indexExpr === '*') {
  411. // 通配符:所有元素
  412. current.forEach((item, index) => {
  413. this.evaluateJsonPath(item, remainPath, currentPath + '[' + index + ']', results);
  414. });
  415. } else if (indexExpr.includes(':')) {
  416. // 数组切片 [start:end]
  417. let [start, end] = indexExpr.split(':').map(s => s.trim() === '' ? undefined : parseInt(s));
  418. let sliced = current.slice(start, end);
  419. sliced.forEach((item, index) => {
  420. let actualIndex = (start || 0) + index;
  421. this.evaluateJsonPath(item, remainPath, currentPath + '[' + actualIndex + ']', results);
  422. });
  423. } else if (indexExpr.startsWith('?(')) {
  424. // 过滤表达式 [?(@.prop)]
  425. current.forEach((item, index) => {
  426. if (this.evaluateFilter(item, indexExpr)) {
  427. this.evaluateJsonPath(item, remainPath, currentPath + '[' + index + ']', results);
  428. }
  429. });
  430. } else {
  431. // 具体索引
  432. let index = parseInt(indexExpr);
  433. if (index < 0) {
  434. index = current.length + index; // 负索引
  435. }
  436. if (index >= 0 && index < current.length) {
  437. this.evaluateJsonPath(current[index], remainPath, currentPath + '[' + index + ']', results);
  438. }
  439. }
  440. return;
  441. }
  442. // 处理属性访问 .property 或直接属性名
  443. if ((match = path.match(/^\.?([^.\[]+)(.*)$/))) {
  444. let prop = match[1];
  445. let remainPath = match[2];
  446. if (prop === '*') {
  447. // 通配符:所有属性
  448. if (typeof current === 'object' && current !== null) {
  449. Object.keys(current).forEach(key => {
  450. this.evaluateJsonPath(current[key], remainPath, currentPath + '.' + key, results);
  451. });
  452. }
  453. } else {
  454. // 具体属性
  455. if (typeof current === 'object' && current !== null && current.hasOwnProperty(prop)) {
  456. this.evaluateJsonPath(current[prop], remainPath, currentPath + '.' + prop, results);
  457. }
  458. }
  459. return;
  460. }
  461. // 处理方括号属性访问 ['property']
  462. if ((match = path.match(/^\['([^']+)'\](.*)$/))) {
  463. let prop = match[1];
  464. let remainPath = match[2];
  465. if (typeof current === 'object' && current !== null && current.hasOwnProperty(prop)) {
  466. this.evaluateJsonPath(current[prop], remainPath, currentPath + "['" + prop + "']", results);
  467. }
  468. return;
  469. }
  470. // 如果没有特殊符号,当作属性名处理
  471. if (typeof current === 'object' && current !== null && current.hasOwnProperty(path)) {
  472. results.push({ path: currentPath + '.' + path, value: current[path] });
  473. }
  474. },
  475. // 递归搜索
  476. recursiveSearch: function(current, targetProp, currentPath, results) {
  477. if (typeof current === 'object' && current !== null) {
  478. // 检查当前对象的属性
  479. if (current.hasOwnProperty(targetProp)) {
  480. results.push({ path: currentPath + '..' + targetProp, value: current[targetProp] });
  481. }
  482. // 递归搜索子对象
  483. Object.keys(current).forEach(key => {
  484. if (Array.isArray(current[key])) {
  485. current[key].forEach((item, index) => {
  486. this.recursiveSearch(item, targetProp, currentPath + '.' + key + '[' + index + ']', results);
  487. });
  488. } else if (typeof current[key] === 'object' && current[key] !== null) {
  489. this.recursiveSearch(current[key], targetProp, currentPath + '.' + key, results);
  490. }
  491. });
  492. }
  493. },
  494. // 简单的过滤器评估
  495. evaluateFilter: function(item, filterExpr) {
  496. // 简化的过滤器实现,只支持基本的属性存在性检查
  497. // 如 ?(@.name) 检查是否有name属性
  498. let match = filterExpr.match(/^\?\(@\.(\w+)\)$/);
  499. if (match) {
  500. let prop = match[1];
  501. return typeof item === 'object' && item !== null && item.hasOwnProperty(prop);
  502. }
  503. // 支持简单的比较 ?(@.age > 18)
  504. match = filterExpr.match(/^\?\(@\.(\w+)\s*([><=!]+)\s*(.+)\)$/);
  505. if (match) {
  506. let prop = match[1];
  507. let operator = match[2];
  508. let value = match[3];
  509. if (typeof item === 'object' && item !== null && item.hasOwnProperty(prop)) {
  510. let itemValue = item[prop];
  511. let compareValue = isNaN(value) ? value.replace(/['"]/g, '') : parseFloat(value);
  512. switch (operator) {
  513. case '>': return itemValue > compareValue;
  514. case '<': return itemValue < compareValue;
  515. case '>=': return itemValue >= compareValue;
  516. case '<=': return itemValue <= compareValue;
  517. case '==': return itemValue == compareValue;
  518. case '!=': return itemValue != compareValue;
  519. }
  520. }
  521. }
  522. return false;
  523. },
  524. // 显示JSONPath示例
  525. showJsonPathExamples: function() {
  526. this.showJsonPathExamplesModal = true;
  527. },
  528. // 使用JSONPath示例
  529. useJsonPathExample: function(path) {
  530. this.jsonPathQuery = path;
  531. this.closeJsonPathExamplesModal();
  532. },
  533. // 打开JSONPath查询模态框
  534. openJsonPathModal: function() {
  535. this.showJsonPathModal = true;
  536. // 清空之前的查询结果
  537. this.jsonPathResults = [];
  538. this.jsonPathError = '';
  539. this.copyButtonState = 'normal';
  540. },
  541. // 关闭JSONPath结果模态框
  542. closeJsonPathModal: function() {
  543. this.showJsonPathModal = false;
  544. this.copyButtonState = 'normal'; // 重置复制按钮状态
  545. },
  546. // 关闭JSONPath示例模态框
  547. closeJsonPathExamplesModal: function() {
  548. this.showJsonPathExamplesModal = false;
  549. },
  550. // 格式化JSONPath查询结果
  551. formatJsonPathResult: function(value) {
  552. if (typeof value === 'object') {
  553. return JSON.stringify(value, null, 2);
  554. }
  555. return String(value);
  556. },
  557. // 复制JSONPath查询结果
  558. copyJsonPathResults: function() {
  559. let resultText = this.jsonPathResults.map(result => {
  560. return `路径: ${result.path}\n值: ${this.formatJsonPathResult(result.value)}`;
  561. }).join('\n\n');
  562. // 设置复制状态
  563. this.copyButtonState = 'copying';
  564. navigator.clipboard.writeText(resultText).then(() => {
  565. this.copyButtonState = 'success';
  566. setTimeout(() => {
  567. this.copyButtonState = 'normal';
  568. }, 2000);
  569. }).catch(() => {
  570. // 兼容旧浏览器
  571. try {
  572. let textArea = document.createElement('textarea');
  573. textArea.value = resultText;
  574. document.body.appendChild(textArea);
  575. textArea.select();
  576. document.execCommand('copy');
  577. document.body.removeChild(textArea);
  578. this.copyButtonState = 'success';
  579. setTimeout(() => {
  580. this.copyButtonState = 'normal';
  581. }, 2000);
  582. } catch (error) {
  583. this.copyButtonState = 'error';
  584. setTimeout(() => {
  585. this.copyButtonState = 'normal';
  586. }, 2000);
  587. }
  588. });
  589. },
  590. // 下载JSONPath查询结果
  591. downloadJsonPathResults: function() {
  592. let resultText = this.jsonPathResults.map(result => {
  593. return `路径: ${result.path}\n值: ${this.formatJsonPathResult(result.value)}`;
  594. }).join('\n\n');
  595. // 基于JSONPath生成文件名
  596. let filename = this.generateFilenameFromPath(this.jsonPathQuery);
  597. let blob = new Blob([resultText], { type: 'text/plain;charset=utf-8' });
  598. let url = window.URL.createObjectURL(blob);
  599. let a = document.createElement('a');
  600. a.href = url;
  601. a.download = filename + '.txt';
  602. document.body.appendChild(a);
  603. a.click();
  604. document.body.removeChild(a);
  605. window.URL.revokeObjectURL(url);
  606. },
  607. // 根据JSONPath生成文件名
  608. generateFilenameFromPath: function(path) {
  609. if (!path || path === '$') {
  610. return 'jsonpath_root';
  611. }
  612. // 移除开头的$和.
  613. let cleanPath = path.replace(/^\$\.?/, '');
  614. // 替换特殊字符为下划线,保留数字、字母、点号、中划线
  615. let filename = cleanPath
  616. .replace(/[\[\]]/g, '_') // 方括号替换为下划线
  617. .replace(/[^\w\u4e00-\u9fa5.-]/g, '_') // 特殊字符替换为下划线,保留中文
  618. .replace(/_{2,}/g, '_') // 多个连续下划线合并为一个
  619. .replace(/^_|_$/g, ''); // 移除开头和结尾的下划线
  620. // 如果处理后为空,使用默认名称
  621. if (!filename) {
  622. return 'jsonpath_query';
  623. }
  624. // 限制文件名长度
  625. if (filename.length > 50) {
  626. filename = filename.substring(0, 50) + '_truncated';
  627. }
  628. return 'jsonpath_' + filename;
  629. },
  630. jumpToMockDataTool: function(event) {
  631. event.preventDefault();
  632. // 1. 先判断mock-data工具是否已安装
  633. // 方案:直接读取chrome.storage.local,判断DYNAMIC_TOOL:mock-data是否存在
  634. if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
  635. chrome.storage.local.get('DYNAMIC_TOOL:mock-data', result => {
  636. if (result && result['DYNAMIC_TOOL:mock-data']) {
  637. // 已安装,直接打开mock-data工具
  638. window.open('/mock-data/index.html', '_blank');
  639. } else {
  640. // 未安装,跳转到原href
  641. window.open('/options/index.html?query=数据Mock工具', '_blank');
  642. }
  643. });
  644. } else {
  645. // 兜底:如果无法访问chrome.storage,直接跳原href
  646. window.open('/options/index.html?query=数据Mock工具', '_blank');
  647. }
  648. }
  649. }
  650. });
  651. // 新增:递归解包嵌套JSON字符串的函数
  652. function deepParseJSONStrings(obj) {
  653. if (Array.isArray(obj)) {
  654. return obj.map(deepParseJSONStrings);
  655. } else if (typeof obj === 'object' && obj !== null) {
  656. const newObj = {};
  657. for (const key in obj) {
  658. if (!obj.hasOwnProperty(key)) continue;
  659. const val = obj[key];
  660. if (typeof val === 'string') {
  661. try {
  662. const parsed = JSON.parse(val);
  663. // 只递归对象或数组,且排除BigInt结构(如{s,e,c})和纯数字
  664. if (
  665. typeof parsed === 'object' &&
  666. parsed !== null &&
  667. (Array.isArray(parsed) || Object.prototype.toString.call(parsed) === '[object Object]') &&
  668. !(
  669. parsed &&
  670. typeof parsed.s === 'number' &&
  671. typeof parsed.e === 'number' &&
  672. Array.isArray(parsed.c) &&
  673. Object.keys(parsed).length === 3
  674. )
  675. ) {
  676. newObj[key] = deepParseJSONStrings(parsed);
  677. continue;
  678. }
  679. } catch (e) {}
  680. }
  681. newObj[key] = deepParseJSONStrings(val);
  682. }
  683. return newObj;
  684. }
  685. return obj;
  686. }