index.js 36 KB

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