1+ const inputArea = document . getElementById ( 'inputData' ) ;
2+ const outputArea = document . getElementById ( 'outputData' ) ;
3+ const errorDisplay = document . getElementById ( 'errorDisplay' ) ;
4+
5+ function clearError ( ) {
6+ errorDisplay . textContent = '' ;
7+ }
8+
9+ function convertToCsv ( ) {
10+ clearError ( ) ;
11+ const jsonInput = inputArea . value . trim ( ) ;
12+ if ( ! jsonInput ) {
13+ errorDisplay . textContent = 'Please enter JSON data.' ;
14+ outputArea . value = '' ;
15+ return ;
16+ }
17+
18+ try {
19+ const jsonData = JSON . parse ( jsonInput ) ;
20+ if ( ! Array . isArray ( jsonData ) ) {
21+ errorDisplay . textContent = 'Input must be a JSON array of objects.' ;
22+ outputArea . value = '' ;
23+ return ;
24+ }
25+ if ( jsonData . length === 0 ) {
26+ outputArea . value = '' ;
27+ return ;
28+ }
29+
30+ const headers = Object . keys ( jsonData [ 0 ] ) ;
31+ const csvRows = [ ] ;
32+ csvRows . push ( headers . join ( ',' ) ) ;
33+
34+ for ( const row of jsonData ) {
35+ const values = headers . map ( header => {
36+ const escaped = ( '' + row [ header ] ) . replace ( / " / g, '""' ) ;
37+ return `"${ escaped } "` ;
38+ } ) ;
39+ csvRows . push ( values . join ( ',' ) ) ;
40+ }
41+
42+ outputArea . value = csvRows . join ( '\n' ) ;
43+ } catch ( e ) {
44+ console . error ( "JSON to CSV Error:" , e ) ;
45+ if ( e instanceof SyntaxError ) {
46+ errorDisplay . textContent = `JSON Parsing Error: ${ e . message } ` ;
47+ } else {
48+ errorDisplay . textContent = `CSV Conversion Error: ${ e . message } ` ;
49+ }
50+ outputArea . value = '' ;
51+ }
52+ }
53+
54+ function copyToClipboard ( ) {
55+ if ( ! outputArea . value ) return ;
56+ navigator . clipboard . writeText ( outputArea . value ) . then ( ( ) => {
57+ const icon = document . querySelector ( '.copy-icon' ) ;
58+ const originalPath = icon . innerHTML ;
59+ icon . innerHTML = `<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>` ;
60+ setTimeout ( ( ) => {
61+ icon . innerHTML = originalPath ;
62+ } , 2000 ) ;
63+ } ) . catch ( err => {
64+ alert ( '无法复制到剪贴板: ' + err ) ;
65+ } ) ;
66+ }
0 commit comments