├── .github ├── demo.gif └── demo.yml ├── .gitignore ├── .goreleaser.yml ├── Formula └── json2struct.rb ├── LICENSE ├── Makefile ├── README.md ├── cmd ├── root.go └── root_test.go ├── go.mod ├── go.sum ├── main.go └── pkg ├── editor ├── editor.go └── editor_test.go ├── generator ├── generator.go ├── generator_test.go └── testdata │ ├── 1 │ ├── 2 │ ├── 3 │ ├── 4 │ ├── 5 │ ├── 6 │ ├── 7 │ ├── 8 │ ├── 9 │ ├── 10 │ ├── 11 │ ├── 10_expected │ ├── 11_expected │ ├── 1_expected │ ├── 2_expected │ ├── 3_expected │ ├── 4_expected │ ├── 5_expected │ ├── 6_expected │ ├── 7_expected │ ├── 8_expected │ ├── 9_expected │ ├── big_reddit_response │ ├── big_reddit_response_expected │ ├── nested_equal_objects_in_array │ ├── nested_equal_objects_in_array_expected │ ├── number_1.0 │ ├── number_1.000000000000000005 │ ├── number_1.000000000000000005_expected │ ├── number_1.0_expected │ ├── number_1000000000000000 │ ├── number_10000000000000000999 │ ├── number_10000000000000000999_expected │ ├── number_1000000000000000_expected │ ├── number_1e-999 │ ├── number_1e-999_expected │ ├── number_1e6 │ ├── number_1e6_expected │ ├── object_same_key_same_value │ ├── object_same_key_same_value_expected │ ├── object_same_key_unclear_values │ ├── object_same_key_unclear_values_expected │ ├── string_1_escaped_invalid_codepoint │ ├── string_1_escaped_invalid_codepoint_expected │ ├── string_1_invalid_codepoint │ ├── string_1_invalid_codepoint_expected │ ├── string_2_escaped_invalid_codepoints │ ├── string_2_escaped_invalid_codepoints_expected │ ├── string_2_invalid_codepoints │ ├── string_2_invalid_codepoints_expected │ ├── string_3_escaped_invalid_codepoints │ ├── string_3_escaped_invalid_codepoints_expected │ ├── string_3_invalid_codepoints │ ├── string_3_invalid_codepoints_expected │ ├── string_with_escaped_NULL │ ├── string_with_escaped_NULL_expected │ ├── with_invalid_characters │ └── with_invalid_characters_expected ├── lex ├── lexer.go └── lexer_test.go └── parse ├── parser.go └── parser_test.go /.github/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marhaupe/json2struct/90935814bea2f385e06714a5f07de95ba4e70451/.github/demo.gif -------------------------------------------------------------------------------- /.github/demo.yml: -------------------------------------------------------------------------------- 1 | # The configurations that used for the recording, feel free to edit them 2 | config: 3 | 4 | # Specify a command to be executed 5 | # like `/bin/bash -l`, `ls`, or any other commands 6 | # the default is bash for Linux 7 | # or powershell.exe for Windows 8 | command: /bin/bash -l 9 | 10 | # Specify the current working directory path 11 | # the default is the current working directory path 12 | cwd: /Users/haupma/Entwicklung/privat/json2struct 13 | 14 | # Export additional ENV variables 15 | env: 16 | recording: true 17 | 18 | # Explicitly set the number of columns 19 | # or use `auto` to take the current 20 | # number of columns of your shell 21 | cols: 80 22 | 23 | # Explicitly set the number of rows 24 | # or use `auto` to take the current 25 | # number of rows of your shell 26 | rows: 10 27 | 28 | # Amount of times to repeat GIF 29 | # If value is -1, play once 30 | # If value is 0, loop indefinitely 31 | # If value is a positive number, loop n times 32 | repeat: 0 33 | 34 | # Quality 35 | # 1 - 100 36 | quality: 100 37 | 38 | # Delay between frames in ms 39 | # If the value is `auto` use the actual recording delays 40 | frameDelay: auto 41 | 42 | # Maximum delay between frames in ms 43 | # Ignored if the `frameDelay` isn't set to `auto` 44 | # Set to `auto` to prevent limiting the max idle time 45 | maxIdleTime: 5000 46 | 47 | # The surrounding frame box 48 | # The `type` can be null, window, floating, or solid` 49 | # To hide the title use the value null 50 | # Don't forget to add a backgroundColor style with a null as type 51 | frameBox: 52 | type: floating 53 | title: Demo 54 | style: 55 | border: 0px black solid 56 | # boxShadow: none 57 | # margin: 0px 58 | 59 | # Add a watermark image to the rendered gif 60 | # You need to specify an absolute path for 61 | # the image on your machine or a URL, and you can also 62 | # add your own CSS styles 63 | watermark: 64 | imagePath: null 65 | style: 66 | position: absolute 67 | right: 15px 68 | bottom: 15px 69 | width: 100px 70 | opacity: 0.9 71 | 72 | # Cursor style can be one of 73 | # `block`, `underline`, or `bar` 74 | cursorStyle: block 75 | 76 | # Font family 77 | # You can use any font that is installed on your machine 78 | # in CSS-like syntax 79 | fontFamily: "Monaco, Lucida Console, Ubuntu Mono, Monospace" 80 | 81 | # The size of the font 82 | fontSize: 14 83 | 84 | # The height of lines 85 | lineHeight: 1 86 | 87 | # The spacing between letters 88 | letterSpacing: 0 89 | 90 | # Theme 91 | theme: 92 | background: "transparent" 93 | foreground: "#afafaf" 94 | cursor: "#c7c7c7" 95 | black: "#232628" 96 | red: "#fc4384" 97 | green: "#b3e33b" 98 | yellow: "#ffa727" 99 | blue: "#75dff2" 100 | magenta: "#ae89fe" 101 | cyan: "#708387" 102 | white: "#d5d5d0" 103 | brightBlack: "#626566" 104 | brightRed: "#ff7fac" 105 | brightGreen: "#c8ed71" 106 | brightYellow: "#ebdf86" 107 | brightBlue: "#75dff2" 108 | brightMagenta: "#ae89fe" 109 | brightCyan: "#b1c6ca" 110 | brightWhite: "#f9f9f4" 111 | 112 | # Records, feel free to edit them 113 | records: 114 | - delay: 0 115 | content: "\e[?1034h " 116 | - delay: 80 117 | content: j 118 | - delay: 80 119 | content: s 120 | - delay: 80 121 | content: o 122 | - delay: 80 123 | content: 'n' 124 | - delay: 80 125 | content: '2' 126 | - delay: 80 127 | content: s 128 | - delay: 80 129 | content: t 130 | - delay: 80 131 | content: r 132 | - delay: 80 133 | content: u 134 | - delay: 80 135 | content: c 136 | - delay: 80 137 | content: t 138 | - delay: 80 139 | content: "\r\n" 140 | - delay: 80 141 | content: "\e[?2004h\e[?1049h\e[?1h\e=\e[?2004h\e[1;25r\e[?12h\e[?12l\e[27m\e[29m\e[m\e[38;5;252m\e[48;5;234m\e[H\e[2J\e[?25l\e[24;1H\".jsontostruct_temp\" 0L, 0C" 142 | - delay: 80 143 | content: "\e[2;1H▽\e[6n\e[2;1H \e[1;1H\e[>c\e]11;?\a\e[1;1H\e[38;5;252m\e[48;5;235m 1 .jsontostruct_temp \e[m\e[38;5;252m\e[48;5;234m\e[38;5;235m\e[48;5;238m \e[m\e[38;5;252m\e[48;5;234m\e[38;5;248m\e[48;5;238m \e[m\e[38;5;252m\e[48;5;234m\e[38;5;242m\e[48;5;238m \e[m\e[38;5;252m\e[48;5;234m\e[38;5;248m\e[48;5;242m X \e[m\e[38;5;252m\e[48;5;234m\e[2;1H\e[38;5;242m \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \e[m\e[38;5;252m\e[48;5;234m\e[3;2H\e[38;5;69m\e[48;5;233m~ \e[4;2H~ \e[5;2H~ \e[6;2H~ \e[7;2H~ \e[8;2H~ \e[9;2H~ \e[10;2H~ \e[11;2H~ \e[12;2H~ \e[13;2H~ \e[14;2H~ \e[15;2H~ \e[16;2H~ \e[17;2H~ \e[18;2H~ \e[19;2H~ \e[20;2H~ \e[21;2H~ \e[22;2H~ \e[?25h\e[?12$p" 144 | - delay: 80 145 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234m\e[25;1H\e[38;5;252m\e[48;5;18m-- INSERT --\e[m\e[38;5;252m\e[48;5;234m\e[23;1H\e[38;5;238m\e[48;5;119m INSERT \e[m\e[38;5;252m\e[48;5;234m\e[38;5;119m\e[48;5;240m \e[m\e[38;5;252m\e[48;5;234m\e[38;5;252m\e[48;5;240m master .jsontostruct_temp \e[m\e[38;5;252m\e[48;5;234m\e[38;5;240m\e[48;5;238m \e[m\e[38;5;252m\e[48;5;234m\e[38;5;248m\e[48;5;238m \e[m\e[38;5;252m\e[48;5;234m\e[38;5;240m\e[48;5;238m \e[m\e[38;5;252m\e[48;5;234m\e[38;5;247m\e[48;5;240m 100% \e[m\e[38;5;252m\e[48;5;234m\e[38;5;244m\e[48;5;240m \e[m\e[38;5;252m\e[48;5;234m\e[38;5;238m\e[48;5;244m 0:1 \e[2;2H\e[?25h" 146 | - delay: 80 147 | content: "\e[?2004h\e[m\e[38;5;252m\e[48;5;234m\e[1;23H\e[38;5;252m\e[48;5;235m+ \e[m\e[38;5;252m\e[48;5;234m\e[38;5;235m\e[48;5;238m \e[?25l\e[m\e[38;5;252m\e[48;5;234m\e[2;2H\e[48;5;90m{}\e[m\e[38;5;252m\e[48;5;234m\e[23;39H\e[38;5;252m\e[48;5;240m + \e[m\e[38;5;252m\e[48;5;234m\e[38;5;240m\e[48;5;238m \e[m\e[38;5;252m\e[48;5;234m\e[32C\e[38;5;238m\e[48;5;244m1:2\e[2;3H\e[?25h" 148 | - delay: 80 149 | content: "\e[?2004h\e[m\e[38;5;252m\e[48;5;234m\e[25;1H\e[K\e[?25l\e[24;1H\e[K\e[25;1H\e[38;5;252m\e[48;5;18m-- INSERT --\e[m\e[38;5;252m\e[48;5;234m\e[2;2H{\e[2;3H\e[K\e[3;2H \e[3;6H\e[K\e[4;2H}\e[4;3H\e[K\e[23;67H\e[38;5;247m\e[48;5;240m 66\e[m\e[38;5;252m\e[48;5;234m\e[6C\e[38;5;238m\e[48;5;244m2:5\e[3;6H\e[?25h" 150 | - delay: 80 151 | content: "\e[?2004h\e[?25l\e[m\e[38;5;252m\e[48;5;234m\"\"\e[23;78H\e[38;5;238m\e[48;5;244m6\e[3;7H\e[?25h" 152 | - delay: 80 153 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mH\"\e[23;78H\e[38;5;238m\e[48;5;244m7\e[3;8H\e[?25h" 154 | - delay: 80 155 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234me\"\e[23;78H\e[38;5;238m\e[48;5;244m8\e[3;9H\e[?25h" 156 | - delay: 80 157 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234my\"\e[23;78H\e[38;5;238m\e[48;5;244m9\e[3;10H\e[?25h" 158 | - delay: 80 159 | content: "\e[?2004h\e[23;78H10\e[3;11H" 160 | - delay: 80 161 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234m:\e[23;79H\e[38;5;238m\e[48;5;244m1\e[3;12H\e[?25h" 162 | - delay: 80 163 | content: "\e[?2004h\e[?25l\e[23;79H2\e[3;13H\e[?25h" 164 | - delay: 80 165 | content: "\e[?2004h\e[?25l\e[m\e[38;5;252m\e[48;5;234m\"\"\e[23;79H\e[38;5;238m\e[48;5;244m3\e[3;14H\e[?25h" 166 | - delay: 80 167 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mH\"\e[23;79H\e[38;5;238m\e[48;5;244m4\e[3;15H\e[?25h" 168 | - delay: 80 169 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mi\"\e[23;79H\e[38;5;238m\e[48;5;244m5\e[3;16H\e[?25h" 170 | - delay: 80 171 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234m!\"\e[23;79H\e[38;5;238m\e[48;5;244m6\e[3;17H\e[?25h" 172 | - delay: 80 173 | content: "\e[?2004h\e[23;79H7\e[3;18H" 174 | - delay: 80 175 | content: "\e[m\e[38;5;252m\e[48;5;234m,\b" 176 | - delay: 80 177 | content: " \b\e[?2004h\e[?25l\e[4;22r\e[4;1H\e[L\e[1;25r\e[3;18H,\r\n\e[38;5;242m \e[m\e[38;5;252m\e[48;5;234m\e[25;1H\e[K\e[25;1H\e[38;5;252m\e[48;5;18m-- INSERT --\e[m\e[38;5;252m\e[48;5;234m\e[23;68H\e[38;5;247m\e[48;5;240m75\e[m\e[38;5;252m\e[48;5;234m\e[6C\e[38;5;238m\e[48;5;244m3:5 \e[4;6H\e[?25h" 178 | - delay: 80 179 | content: "\e[?2004h\e[?25l\e[m\e[38;5;252m\e[48;5;234m\"\"\e[23;78H\e[38;5;238m\e[48;5;244m6\e[4;7H\e[?25h" 180 | - delay: 80 181 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mT\"\e[23;78H\e[38;5;238m\e[48;5;244m7\e[4;8H\e[?25h" 182 | - delay: 80 183 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mh\"\e[23;78H\e[38;5;238m\e[48;5;244m8\e[4;9H\e[?25h" 184 | - delay: 80 185 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mi\"\e[23;78H\e[38;5;238m\e[48;5;244m9\e[4;10H\e[?25h" 186 | - delay: 80 187 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234ms\"\e[23;78H\e[38;5;238m\e[48;5;244m10\e[4;11H\e[?25h" 188 | - delay: 80 189 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mI\"\e[23;79H\e[38;5;238m\e[48;5;244m1\e[4;12H\e[?25h" 190 | - delay: 80 191 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234ms\"\e[23;79H\e[38;5;238m\e[48;5;244m2\e[4;13H\e[?25h" 192 | - delay: 80 193 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mW\"\e[23;79H\e[38;5;238m\e[48;5;244m3\e[4;14H\e[?25h" 194 | - delay: 80 195 | content: "\e[?2004h\e[?25l\e[m\e[38;5;252m\e[48;5;234m\b\"\e[4;14H\e[K\e[23;79H\e[38;5;238m\e[48;5;244m2\e[4;13H\e[?25h" 196 | - delay: 80 197 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mA\"\e[23;79H\e[38;5;238m\e[48;5;244m3\e[4;14H\e[?25h" 198 | - delay: 80 199 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mw\"\e[23;79H\e[38;5;238m\e[48;5;244m4\e[4;15H\e[?25h" 200 | - delay: 80 201 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234me\"\e[23;79H\e[38;5;238m\e[48;5;244m5\e[4;16H\e[?25h" 202 | - delay: 80 203 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234ms\"\e[23;79H\e[38;5;238m\e[48;5;244m6\e[4;17H\e[?25h" 204 | - delay: 80 205 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mo\"\e[23;79H\e[38;5;238m\e[48;5;244m7\e[4;18H\e[?25h" 206 | - delay: 80 207 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mm\"\e[23;79H\e[38;5;238m\e[48;5;244m8\e[4;19H\e[?25h" 208 | - delay: 80 209 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234me\"\e[23;79H\e[38;5;238m\e[48;5;244m9\e[4;20H\e[?25h" 210 | - delay: 80 211 | content: "\e[?2004h\e[23;78H20\e[4;21H" 212 | - delay: 80 213 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234m:\e[23;79H\e[38;5;238m\e[48;5;244m1\e[4;22H\e[?25h" 214 | - delay: 80 215 | content: "\e[?2004h\e[?25l\e[23;79H2\e[4;23H\e[?25h" 216 | - delay: 80 217 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mt\e[23;79H\e[38;5;238m\e[48;5;244m3\e[4;24H\e[?25h" 218 | - delay: 80 219 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mr\e[23;79H\e[38;5;238m\e[48;5;244m4\e[4;25H\e[?25h" 220 | - delay: 80 221 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234me\e[23;79H\e[38;5;238m\e[48;5;244m5\e[4;26H\e[?25h" 222 | - delay: 80 223 | content: "\e[?2004h\e[?25l\e[m\e[38;5;252m\e[48;5;234m\e[4;25H\e[K\e[23;79H\e[38;5;238m\e[48;5;244m4\e[4;25H\e[?25h" 224 | - delay: 80 225 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mu\e[23;79H\e[38;5;238m\e[48;5;244m5\e[4;26H\e[?25h" 226 | - delay: 80 227 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234me\e[23;79H\e[38;5;238m\e[48;5;244m6\e[4;27H\e[?25h" 228 | - delay: 80 229 | content: "\e[m\e[38;5;252m\e[48;5;234m,\b" 230 | - delay: 80 231 | content: " \b\e[?2004h\e[?25l\e[5;22r\e[5;1H\e[L\e[1;25r\e[4;27H,\r\n\e[38;5;242m \e[m\e[38;5;252m\e[48;5;234m\e[25;1H\e[K\e[25;1H\e[38;5;252m\e[48;5;18m-- INSERT --\e[m\e[38;5;252m\e[48;5;234m\e[23;68H\e[38;5;247m\e[48;5;240m80\e[m\e[38;5;252m\e[48;5;234m\e[6C\e[38;5;238m\e[48;5;244m4:5 \e[5;6H\e[?25h" 232 | - delay: 80 233 | content: "\e[?2004h\e[?25l\e[m\e[38;5;252m\e[48;5;234m\"\"\e[23;78H\e[38;5;238m\e[48;5;244m6\e[5;7H\e[?25h" 234 | - delay: 80 235 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mC\"\e[23;78H\e[38;5;238m\e[48;5;244m7\e[5;8H\e[?25h" 236 | - delay: 80 237 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mh\"\e[23;78H\e[38;5;238m\e[48;5;244m8\e[5;9H\e[?25h" 238 | - delay: 80 239 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234me\"\e[23;78H\e[38;5;238m\e[48;5;244m9\e[5;10H\e[?25h" 240 | - delay: 80 241 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mc\"\e[23;78H\e[38;5;238m\e[48;5;244m10\e[5;11H\e[?25h" 242 | - delay: 80 243 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mk\"\e[23;79H\e[38;5;238m\e[48;5;244m1\e[5;12H\e[?25h" 244 | - delay: 80 245 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mI\"\e[23;79H\e[38;5;238m\e[48;5;244m2\e[5;13H\e[?25h" 246 | - delay: 80 247 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mt\"\e[23;79H\e[38;5;238m\e[48;5;244m3\e[5;14H\e[?25h" 248 | - delay: 80 249 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mO\"\e[23;79H\e[38;5;238m\e[48;5;244m4\e[5;15H\e[?25h" 250 | - delay: 80 251 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mu\"\e[23;79H\e[38;5;238m\e[48;5;244m5\e[5;16H\e[?25h" 252 | - delay: 80 253 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mt\"\e[23;79H\e[38;5;238m\e[48;5;244m6\e[5;17H\e[?25h" 254 | - delay: 80 255 | content: "\e[?2004h\e[23;79H7\e[5;18H" 256 | - delay: 80 257 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234m:\e[23;79H\e[38;5;238m\e[48;5;244m8\e[5;19H\e[?25h" 258 | - delay: 80 259 | content: "\e[?2004h\e[?25l\e[23;79H9\e[5;20H\e[?25h" 260 | - delay: 80 261 | content: "\e[?2004h\e[?25l\e[m\e[38;5;252m\e[48;5;234m\"\"\e[23;78H\e[38;5;238m\e[48;5;244m20\e[5;21H\e[?25h" 262 | - delay: 80 263 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mI\"\e[23;79H\e[38;5;238m\e[48;5;244m1\e[5;22H\e[?25h" 264 | - delay: 80 265 | content: "\e[?2004h\e[?25l\e[m\e[38;5;252m\e[48;5;234m \"\e[23;79H\e[38;5;238m\e[48;5;244m2\e[5;23H\e[?25h" 266 | - delay: 80 267 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mW\"\e[23;79H\e[38;5;238m\e[48;5;244m3\e[5;24H\e[?25h" 268 | - delay: 80 269 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234mi\"\e[23;79H\e[38;5;238m\e[48;5;244m4\e[5;25H\e[?25h" 270 | - delay: 80 271 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234ml\"\e[23;79H\e[38;5;238m\e[48;5;244m5\e[5;26H\e[?25h" 272 | - delay: 80 273 | content: "\e[?25l\e[m\e[38;5;252m\e[48;5;234ml\"\e[23;79H\e[38;5;238m\e[48;5;244m6\e[5;27H\e[?25h" 274 | - delay: 80 275 | content: "\e[?2004h\e[23;79H7\e[5;28H" 276 | - delay: 80 277 | content: "\e[m\e[38;5;252m\e[48;5;234m,\b" 278 | - delay: 80 279 | content: " \b\e[?25l,\e[23;79H\e[38;5;238m\e[48;5;244m8\e[5;29H\e[?25h" 280 | - delay: 80 281 | content: "\e[?2004h\e[?25l\e[m\e[38;5;252m\e[48;5;234m\e[5;28H\e[K\e[23;79H\e[38;5;238m\e[48;5;244m7\e[5;28H\e[?25h" 282 | - delay: 80 283 | content: "\e[m\e[38;5;252m\e[48;5;234m\e[25;1H\e[K\e[5;27H" 284 | - delay: 80 285 | content: "\e[?25l\e[23;1H\e[38;5;238m\e[48;5;117m NORMAL \e[m\e[38;5;252m\e[48;5;234m\e[38;5;117m\e[48;5;240m \e[m\e[38;5;252m\e[48;5;234m\e[69C\e[38;5;238m\e[48;5;244m6\e[?25h\e[?25l\r\n\e[m\e[38;5;252m\e[48;5;234m:\e[?2004h\e[?25h" 286 | - delay: 80 287 | content: w 288 | - delay: 80 289 | content: q 290 | - delay: 1000 291 | content: "\r\e[?25l\e[?2004l\".jsontostruct_temp\" 5L, 76C written" 292 | - delay: 80 293 | content: "\r\r\n\r\r\n\r\r\n\e[39;49m\e[?2004l\e[?1l\e>\e[?25h\e[?1049lpackage generated\r\n\r\ntype JSONToStruct struct {\r\n\tCheckitout string `json:\"CheckItOut\"`\r\n\tHey string `json:\"Hey\"`\r\n\tThisisawesome bool `json:\"ThisIsAwesome\"`\r\n}\r\n\r\n " 294 | - delay: 4000 295 | content: "logout\r\n" 296 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | cover.* 2 | json2struct 3 | dist 4 | .vscode -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | before: 3 | hooks: 4 | - make clean 5 | 6 | builds: 7 | - main: ./main.go 8 | binary: json2struct 9 | ldflags: 10 | - -s -w -X github.com/marhaupe/json2struct/cmd.version={{.Version}} 11 | goos: 12 | - darwin 13 | - linux 14 | - windows 15 | env: 16 | - CGO_ENABLED=0 17 | 18 | archives: 19 | - name_template: >- 20 | {{- .ProjectName }}_ 21 | {{- title .Os }}_ 22 | {{- if eq .Arch "amd64" }}x86_64 23 | {{- else if eq .Arch "386" }}i386 24 | {{- else }}{{ .Arch }}{{ end }} 25 | {{- if .Arm }}v{{ .Arm }}{{ end -}} 26 | format_overrides: 27 | - goos: windows 28 | formats: [zip] 29 | brews: 30 | - repository: 31 | owner: marhaupe 32 | name: json2struct 33 | commit_author: 34 | name: Marcel Haupenthal 35 | email: marhaupe97@gmail.com 36 | directory: Formula 37 | dependencies: 38 | - git -------------------------------------------------------------------------------- /Formula/json2struct.rb: -------------------------------------------------------------------------------- 1 | # typed: false 2 | # frozen_string_literal: true 3 | 4 | # This file was generated by GoReleaser. DO NOT EDIT. 5 | class Json2struct < Formula 6 | desc "" 7 | homepage "" 8 | version "1.9.3" 9 | 10 | depends_on "git" 11 | 12 | on_macos do 13 | if Hardware::CPU.intel? 14 | url "https://github.com/marhaupe/json2struct/releases/download/v1.9.3/json2struct_Darwin_x86_64.tar.gz" 15 | sha256 "2e774b5fce22a1b496f5344312b9a171ef0bfcf7f84ce60e83028ac9555a64af" 16 | 17 | def install 18 | bin.install "json2struct" 19 | end 20 | end 21 | if Hardware::CPU.arm? 22 | url "https://github.com/marhaupe/json2struct/releases/download/v1.9.3/json2struct_Darwin_arm64.tar.gz" 23 | sha256 "45cf33254a5ae8e08f9c6535b73b10df273392bcc95c33a6690bd1def61a904e" 24 | 25 | def install 26 | bin.install "json2struct" 27 | end 28 | end 29 | end 30 | 31 | on_linux do 32 | if Hardware::CPU.intel? 33 | if Hardware::CPU.is_64_bit? 34 | url "https://github.com/marhaupe/json2struct/releases/download/v1.9.3/json2struct_Linux_x86_64.tar.gz" 35 | sha256 "ff16b2ed3ba7d0b741c1ceb021390897d04646cb9aea281925a3d9decadec3e1" 36 | 37 | def install 38 | bin.install "json2struct" 39 | end 40 | end 41 | end 42 | if Hardware::CPU.arm? 43 | if Hardware::CPU.is_64_bit? 44 | url "https://github.com/marhaupe/json2struct/releases/download/v1.9.3/json2struct_Linux_arm64.tar.gz" 45 | sha256 "79c0f0689ed5635c3765469c01954d9b10ccc9f2736f9c27f8c5334fef344372" 46 | 47 | def install 48 | bin.install "json2struct" 49 | end 50 | end 51 | end 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | OUTPUT?="json2struct" 2 | VERSION=$(shell git describe --tags) 3 | LDFLAGS="-X github.com/marhaupe/json2struct/cmd.version=$(VERSION)" 4 | 5 | .PHONY: build install test testrace clean coverage 6 | 7 | build: 8 | CGO_ENABLED=0 go build -o $(OUTPUT) -ldflags=$(LDFLAGS) 9 | 10 | install: 11 | CGO_ENABLED=0 go install -ldflags=$(LDFLAGS) 12 | 13 | test: 14 | go test ./... 15 | 16 | testrace: 17 | go test -race ./... 18 | 19 | clean: 20 | rm -rf dist 21 | 22 | benchmark: 23 | go test -cpuprofile cpu.prof -memprofile mem.prof -bench ^BenchmarkLargeFile github.com/marhaupe/json2struct/pkg/generator 24 | 25 | coverage: 26 | go test ./... -coverprofile cover.out 27 | go tool cover -html=cover.out -o cover.html 28 | rm cover.out 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # json2struct 2 | 3 | [![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) 4 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com) 5 | 6 | 7 | 8 | > CLI tool to convert JSON to struct type definitions 9 | 10 | At some point when dealing with JSONs in Go, you will have to write struct types to `json.Unmarshal` your JSONs into. Doing this by hand is not only repetitive and time consuming, but also error prone. `json2struct` saves you this work by automatically parsing the JSON and generating you the matching struct type definitions ready to be used. 11 | 12 | Unlike other tools, `json2struct` tries to avoid generating `interface{}` and `map[string]interface{}` as much as possible. Nonetheless it's very [fast](#benchmarks) 🚀. 13 | 14 | ## Installation 15 | 16 | ### Homebrew 17 | 18 | ```bash 19 | brew tap marhaupe/json2struct https://github.com/marhaupe/json2struct 20 | 21 | brew install marhaupe/json2struct/json2struct 22 | ``` 23 | 24 | ### Manually 25 | 26 | Grab the latest release [binaries](https://github.com/marhaupe/json2struct/releases). 27 | 28 | ## Usage 29 | 30 | > json2struct [options] 31 | 32 | Calling `json2struct` without flags opens a text editor. Simply input your JSON and save and exit. 33 | 34 | ![Example](.github/demo.gif) 35 | 36 | ### Options 37 | 38 | You probably don't want to manually write that 1MB JSON you have to generate a struct for by hand. I mean, if you really want to, I'm not here to judge, but that's not the point. These options will make your life easier. If you miss some, feel free to open an issue. 39 | 40 | #### Generating a struct from a string 41 | 42 | > -s, --string string: JSON string 43 | 44 | This is basically your bread and butter thanks to pipes. Usage: 45 | 46 | ```bash 47 | json2struct -s "$(curl "https://reqres.in/api/users?page=2")" 48 | ``` 49 | 50 | #### Generating a struct from an existing file 51 | 52 | > -f, --file string: path to JSON file 53 | 54 | This is useful if you have a JSON file stored in your filesystem and are too lazy to use pipes. Usage: 55 | 56 | ```bash 57 | json2struct -f input.json 58 | ``` 59 | 60 | #### Generating a struct from the clipboard to the clipboard 61 | 62 | > -c, --clipboard: read from and write types to clipboard 63 | 64 | Reads JSON from clipboard, generates types and writes those types to the clipboard. 65 | 66 | ```bash 67 | json2struct -c 68 | ``` 69 | 70 | #### Other options 71 | 72 | > -b, --benchmark: measure execution time 73 | 74 | > -h, --help: help for json2struct 75 | 76 | > --version: version for json2struct 77 | 78 | 79 | 80 | ## Benchmarks 81 | 82 | | Command | Mean [ms] | Min [ms] | Max [ms] | Relative | 83 | |:---|---:|---:|---:|---:| 84 | | `json2struct -f big_reddit_response` | 8.1 ± 0.6 | 7.3 | 11.3 | 1.00 | 85 | | `gojson -input big_reddit_response` | 9.0 ± 0.5 | 8.1 | 10.8 | 1.12 ± 0.10 | 86 | | `cat big_reddit_response \| gojsonstruct` | 71.7 ± 1.3 | 69.9 | 76.9 | 8.87 ± 0.64 | 87 | | `quicktype -l go -o output.go big_reddit_response` | 329.5 ± 2.2 | 326.7 | 333.5 | 40.75 ± 2.86 | 88 | 89 | ## Specifics 90 | 91 | A lot of the lexing/parsing in this project is inspired by the [`text/template`](https://go.dev/src/text/template/) package. Rob Pike also gave a talk about how and why they wrote the package. The link can be found [here](https://www.youtube.com/watch?v=HxaD_trXwRE), and the slides to it [here](https://go.dev/talks/2011/lex.slide#1) 92 | -------------------------------------------------------------------------------- /cmd/root.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "bufio" 5 | "encoding/json" 6 | "fmt" 7 | "os" 8 | "strings" 9 | "time" 10 | 11 | "github.com/atotto/clipboard" 12 | "github.com/marhaupe/json2struct/pkg/editor" 13 | "github.com/marhaupe/json2struct/pkg/generator" 14 | "github.com/marhaupe/json2struct/pkg/parse" 15 | "github.com/spf13/cobra" 16 | ) 17 | 18 | var ( 19 | inputString string 20 | inputFile string 21 | version string 22 | shouldBenchmark bool 23 | shouldUseClipboard bool 24 | 25 | rootCmd = &cobra.Command{ 26 | Use: "json2struct", 27 | Short: "json2struct generates Go type definitions for a JSON", 28 | Version: version, 29 | Args: cobra.ExactArgs(0), 30 | Run: func(cmd *cobra.Command, args []string) { 31 | Run(inputString, inputFile, shouldBenchmark, shouldUseClipboard) 32 | }, 33 | } 34 | ) 35 | 36 | func init() { 37 | rootCmd.Flags().StringVarP(&inputString, "string", "s", "", "JSON string") 38 | rootCmd.Flags().StringVarP(&inputFile, "file", "f", "", "path to JSON file") 39 | rootCmd.Flags().BoolVarP(&shouldBenchmark, "benchmark", "b", false, "measure execution time") 40 | rootCmd.Flags().BoolVarP(&shouldUseClipboard, "clipboard", "c", false, "read from and write types to clipboard") 41 | } 42 | 43 | func Execute() { 44 | err := rootCmd.Execute() 45 | if err != nil { 46 | fmt.Println(err) 47 | } 48 | } 49 | 50 | func Run(inputString, inputFile string, shouldBenchmark, shouldUseClipboard bool) { 51 | if shouldBenchmark { 52 | defer benchmark()() 53 | } 54 | 55 | var userInputNode parse.Node 56 | var err error 57 | 58 | switch { 59 | case shouldUseClipboard: 60 | var userInput string 61 | userInput, err = clipboard.ReadAll() 62 | if err != nil { 63 | fmt.Println(err) 64 | os.Exit(2) 65 | } 66 | userInputNode, err = parse.ParseFromString(userInput) 67 | case inputFile != "": 68 | userInput := readFromFile() 69 | userInputNode, err = parse.ParseFromString(userInput) 70 | case inputString != "": 71 | userInput := inputString 72 | userInputNode, err = parse.ParseFromString(userInput) 73 | default: 74 | userInputNode, err = readFromEditor() 75 | } 76 | 77 | if err != nil { 78 | fmt.Println(err) 79 | os.Exit(1) 80 | } 81 | 82 | if userInputNode == nil { 83 | return 84 | } 85 | 86 | output, err := generator.GenerateOutputFromAST(userInputNode) 87 | if err != nil { 88 | fmt.Println(err) 89 | os.Exit(3) 90 | } 91 | 92 | fmt.Println(output) 93 | 94 | if shouldUseClipboard { 95 | err = clipboard.WriteAll(output) 96 | if err != nil { 97 | fmt.Println(err) 98 | os.Exit(4) 99 | } 100 | fmt.Println("\nSaved output to clipboard") 101 | } 102 | } 103 | 104 | func readFromFile() string { 105 | data, err := os.ReadFile(inputFile) 106 | if err != nil { 107 | fmt.Println(err) 108 | os.Exit(1) 109 | } 110 | return string(data) 111 | } 112 | 113 | func readFromEditor() (parse.Node, error) { 114 | edit := editor.New() 115 | defer edit.Delete() 116 | edit.Display() 117 | 118 | userInput, _ := edit.Read() 119 | 120 | userInputNode, err := parse.ParseFromString(userInput) 121 | if err == nil { 122 | return userInputNode, nil 123 | } 124 | 125 | reader := bufio.NewReader(os.Stdin) 126 | for { 127 | fmt.Print("You supplied invalid JSON. Continue editing? (Y/n) ") 128 | userAnswer, _ := reader.ReadString('\n') 129 | userAnswer = strings.TrimSpace(userAnswer) 130 | userWantsFix := len(userAnswer) == 0 || userAnswer[0] == 'y' 131 | if !userWantsFix { 132 | return nil, nil 133 | } 134 | fmt.Print("\033[1A\033[2K") 135 | edit.Display() 136 | userInput, _ = edit.Read() 137 | isValid := json.Valid([]byte(userInput)) 138 | if isValid { 139 | return userInputNode, nil 140 | } 141 | } 142 | } 143 | 144 | func benchmark() func() { 145 | start := time.Now() 146 | return func() { 147 | fmt.Printf("generating took %v\n", time.Since(start)) 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /cmd/root_test.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import "testing" 4 | 5 | func TestRun(t *testing.T) { 6 | type args struct { 7 | inputString string 8 | inputFile string 9 | shouldBenchmark bool 10 | shouldUseClipboard bool 11 | } 12 | tests := []struct { 13 | name string 14 | args args 15 | }{ 16 | { 17 | name: "should parse input string", 18 | args: args{ 19 | inputString: `{"name": "John", "age": 30}`, 20 | inputFile: "", 21 | shouldBenchmark: false, 22 | shouldUseClipboard: false, 23 | }, 24 | }, 25 | } 26 | for _, tt := range tests { 27 | t.Run(tt.name, func(t *testing.T) { 28 | Run(tt.args.inputString, tt.args.inputFile, tt.args.shouldBenchmark, tt.args.shouldUseClipboard) 29 | }) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/marhaupe/json2struct 2 | 3 | go 1.24 4 | 5 | require ( 6 | github.com/atotto/clipboard v0.1.4 7 | github.com/dave/jennifer v1.7.1 8 | github.com/kylelemons/godebug v1.1.0 9 | github.com/spf13/cobra v1.9.1 10 | ) 11 | 12 | require ( 13 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 14 | github.com/spf13/pflag v1.0.6 // indirect 15 | ) 16 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= 2 | github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= 3 | github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= 4 | github.com/dave/jennifer v1.7.1 h1:B4jJJDHelWcDhlRQxWeo0Npa/pYKBLrirAQoTN45txo= 5 | github.com/dave/jennifer v1.7.1/go.mod h1:nXbxhEmQfOZhWml3D1cDK5M1FLnMSozpbFN/m3RmGZc= 6 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= 7 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= 8 | github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= 9 | github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= 10 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 11 | github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= 12 | github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= 13 | github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= 14 | github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 15 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 16 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 17 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/marhaupe/json2struct/cmd" 5 | ) 6 | 7 | func main() { 8 | cmd.Execute() 9 | } 10 | -------------------------------------------------------------------------------- /pkg/editor/editor.go: -------------------------------------------------------------------------------- 1 | // Package editor contains fields to create, edit, save and then delete files 2 | // with currently only vim 3 | package editor 4 | 5 | import ( 6 | "io/ioutil" 7 | "os" 8 | "os/exec" 9 | ) 10 | 11 | var ( 12 | // defaultEditor is used if $EDITOR is not set 13 | defaultEditor = "vim" 14 | filename = ".jsontostruct_temp" 15 | ) 16 | 17 | // Editor contains fields to display Vim, write contents to a file 18 | // and consume that file and it's contents 19 | type Editor struct { 20 | err error 21 | cmd *exec.Cmd 22 | file *os.File 23 | } 24 | 25 | // New initializes an Editor instance ready to be used 26 | func New() *Editor { 27 | e := &Editor{} 28 | e.setupFile() 29 | e.setupCmd() 30 | return e 31 | } 32 | 33 | func (e *Editor) setupFile() { 34 | e.file, e.err = os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0666) 35 | } 36 | 37 | func (e *Editor) setupCmd() { 38 | editor := getUserEditor() 39 | e.cmd = exec.Command(editor, e.file.Name()) 40 | e.cmd.Stdin = os.Stdin 41 | e.cmd.Stdout = os.Stdout 42 | e.cmd.Stderr = os.Stderr 43 | } 44 | 45 | // Display spawns a new Vim process and pipes stdin, stdout and stderr to it 46 | func (e *Editor) Display() { 47 | if e.cmd.Process != nil { 48 | e.setupCmd() 49 | } 50 | e.cmd.Run() 51 | } 52 | 53 | // Consume consumes the content in the created file and closes and deletes it 54 | func (e *Editor) Consume() (string, error) { 55 | defer e.Delete() 56 | return e.Read() 57 | } 58 | 59 | func (e *Editor) Read() (string, error) { 60 | if e.err != nil { 61 | return "", e.err 62 | } 63 | b, err := ioutil.ReadAll(e.file) 64 | return string(b), err 65 | } 66 | 67 | func (e *Editor) Delete() error { 68 | filename := e.file.Name() 69 | return os.Remove(filename) 70 | } 71 | 72 | func getUserEditor() string { 73 | editor := os.Getenv("EDITOR") 74 | if editor == "" { 75 | return defaultEditor 76 | } 77 | return editor 78 | } 79 | -------------------------------------------------------------------------------- /pkg/editor/editor_test.go: -------------------------------------------------------------------------------- 1 | package editor 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "testing" 7 | ) 8 | 9 | func TestConsumeEmptyFile(t *testing.T) { 10 | editor := New() 11 | content, err := editor.Consume() 12 | editor.Delete() 13 | if content != "" { 14 | t.Error("Content is not empty but should be") 15 | } 16 | if err != nil { 17 | t.Error("Error is not nil but should be") 18 | } 19 | } 20 | 21 | func TestConsumeWithErrors(t *testing.T) { 22 | editor := New() 23 | editor.err = fmt.Errorf("Testerror") 24 | content, err := editor.Consume() 25 | if content != "" { 26 | t.Error("Content is not empty but should be") 27 | } 28 | if err.Error() != fmt.Errorf("Testerror").Error() { 29 | t.Error("Error has not been set properly") 30 | } 31 | } 32 | 33 | func TestNew(t *testing.T) { 34 | editor := New() 35 | if len(editor.cmd.Args) != 2 || editor.cmd.Args[1] != editor.file.Name() { 36 | t.Errorf("Cmd invoked with wrong args %v", editor.cmd.Args) 37 | } 38 | 39 | if editor.cmd.Stdout != os.Stdout || 40 | editor.cmd.Stdin != os.Stdin || 41 | editor.cmd.Stderr != os.Stderr { 42 | t.Error("Cmd pipes have been set wrong") 43 | } 44 | editor.Consume() 45 | } 46 | 47 | func Test_getUserEditor(t *testing.T) { 48 | os.Setenv("EDITOR", "nano") 49 | 50 | editor := getUserEditor() 51 | 52 | if editor != "nano" { 53 | t.Fatalf("want nano but got %v", editor) 54 | } 55 | 56 | os.Unsetenv("EDITOR") 57 | 58 | editor = getUserEditor() 59 | 60 | if editor != defaultEditor { 61 | t.Fatalf("want defaultEditor but got %v", editor) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /pkg/generator/generator.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "fmt" 7 | "sort" 8 | "unicode" 9 | 10 | "github.com/marhaupe/json2struct/pkg/parse" 11 | 12 | "github.com/dave/jennifer/jen" 13 | ) 14 | 15 | func GenerateOutputFromString(s string) (string, error) { 16 | generatedFile, err := generateFileFromString(s) 17 | if err != nil { 18 | return "", err 19 | } 20 | return generateOutput(generatedFile) 21 | } 22 | 23 | func GenerateOutputFromAST(tree parse.Node) (string, error) { 24 | generatedFile, err := generateFileFromAST(tree) 25 | if err != nil { 26 | return "", err 27 | } 28 | return generateOutput(generatedFile) 29 | } 30 | 31 | func generateOutput(generatedFile *jen.File) (string, error) { 32 | buf := &bytes.Buffer{} 33 | err := generatedFile.Render(buf) 34 | if err != nil { 35 | return "", fmt.Errorf("error rendering file: %v", err) 36 | } 37 | return buf.String(), nil 38 | } 39 | 40 | func generateFileFromString(s string) (*jen.File, error) { 41 | node, err := parse.ParseFromString(s) 42 | if err != nil { 43 | return nil, err 44 | } 45 | return generateFileFromAST(node) 46 | } 47 | 48 | func generateFileFromAST(tree parse.Node) (*jen.File, error) { 49 | g := Generator{ 50 | Tree: tree, 51 | currentNode: tree, 52 | file: jen.NewFile("generated"), 53 | } 54 | return g.start() 55 | } 56 | 57 | type Generator struct { 58 | Tree parse.Node 59 | currentNode parse.Node 60 | 61 | file *jen.File 62 | } 63 | 64 | func (g Generator) start() (file *jen.File, err error) { 65 | defer func() { 66 | if r := recover(); r != nil { 67 | file = nil 68 | err = errors.New(fmt.Sprint(r)) 69 | return 70 | } 71 | }() 72 | 73 | rootStmt := g.file.Type().Id("JSONToStruct") 74 | 75 | switch g.Tree.Type() { 76 | case parse.NodeTypeArray: 77 | casted := g.Tree.(*parse.ArrayNode) 78 | rootStmt.Add(makeArray(casted)) 79 | case parse.NodeTypeObject: 80 | casted := g.Tree.(*parse.ObjectNode) 81 | rootStmt.Add(makeStruct(casted)) 82 | default: 83 | panic("invalid json. expected { or [ as initial node but received something else") 84 | } 85 | 86 | return g.file, nil 87 | } 88 | 89 | func makeArray(arr *parse.ArrayNode) *jen.Statement { 90 | // Many different datatypes e.g. strings and objects, 91 | // or no datatypes at all (empty array) 92 | // -> The generated code is []interface{} 93 | childrenTypeCount := countNodeTypes(arr.Children) 94 | if childrenTypeCount != 1 { 95 | return jen.Index().Interface() 96 | } 97 | 98 | // Only arrays as children 99 | // -> The generated code is []interface{} 100 | if arr.Children[0].Type() == parse.NodeTypeArray { 101 | return jen.Index().Interface() 102 | } 103 | 104 | // Only structs as children 105 | // -> We have to merge the structs since we don't 106 | // want to "lose" data when ultimately parsing with 107 | // the generated code. 108 | if arr.Children[0].Type() == parse.NodeTypeObject { 109 | 110 | // Only merge the children objects if the size is greater than one. 111 | if len(arr.Children) > 1 { 112 | mergedObject := mergeObjects(castToObjectArr(arr.Children)) 113 | return jen.Index().Add(makeStruct(mergedObject)) 114 | } 115 | 116 | // At this point, we are sure that there is only one object as a child 117 | return jen.Index().Add(makeStruct(arr.Children[0].(*parse.ObjectNode))) 118 | } 119 | 120 | // Only one primitive datatype e.g. only strings 121 | // -> The generated code is []string 122 | return jen.Index().Add(makePrimTypedef(arr.Children[0].Type())) 123 | } 124 | 125 | func makeStruct(obj *parse.ObjectNode) *jen.Statement { 126 | var children []jen.Code 127 | 128 | var sortedVarnames []string 129 | for varname := range obj.Children { 130 | sortedVarnames = append(sortedVarnames, varname) 131 | } 132 | sort.Strings(sortedVarnames) 133 | 134 | for _, varname := range sortedVarnames { 135 | 136 | valueArray := obj.Children[varname] 137 | childrenWithSharedKey := len(valueArray) 138 | typeCount := countNodeTypes(valueArray) 139 | 140 | if childrenWithSharedKey == 0 { 141 | continue 142 | } 143 | 144 | if childrenWithSharedKey == 1 { 145 | switch valueArray[0].Type() { 146 | case parse.NodeTypeArray: 147 | childArr := valueArray[0].(*parse.ArrayNode) 148 | children = append( 149 | children, 150 | makeId(varname). 151 | Add(makeArray(childArr)). 152 | Add(makeJSONTag(varname)), 153 | ) 154 | case parse.NodeTypeObject: 155 | childObj := valueArray[0].(*parse.ObjectNode) 156 | children = append( 157 | children, 158 | makeId(varname). 159 | Add(makeStruct(childObj)). 160 | Add(makeJSONTag(varname)), 161 | ) 162 | default: 163 | children = append( 164 | children, 165 | makeId(varname). 166 | Add(makePrimTypedef(valueArray[0].Type())). 167 | Add(makeJSONTag(varname)), 168 | ) 169 | } 170 | 171 | } else if childrenWithSharedKey > 1 { 172 | 173 | if typeCount > 1 { 174 | children = append( 175 | children, 176 | makeId(varname). 177 | Add(jen.Interface()). 178 | Add(makeJSONTag(varname)), 179 | ) 180 | 181 | // If there are different objects for the same key, we should merge them together. 182 | } else if typeCount == 1 { 183 | 184 | switch typ := valueArray[0].Type(); typ { 185 | case parse.NodeTypeObject: 186 | compositeObj := mergeObjects(castToObjectArr(valueArray)) 187 | children = append(children, 188 | makeId(varname). 189 | Add(makeStruct(compositeObj)). 190 | Add(makeJSONTag(varname)), 191 | ) 192 | case parse.NodeTypeBool: 193 | fallthrough 194 | case parse.NodeTypeFloat: 195 | fallthrough 196 | case parse.NodeTypeString: 197 | fallthrough 198 | case parse.NodeTypeInteger: 199 | children = append(children, 200 | makeId(varname). 201 | Add(makePrimTypedef(typ)). 202 | Add(makeJSONTag(varname)), 203 | ) 204 | default: 205 | children = append( 206 | children, 207 | makeId(varname). 208 | Add(jen.Interface()). 209 | Add(makeJSONTag(varname)), 210 | ) 211 | 212 | } 213 | } 214 | } 215 | } 216 | 217 | return jen.Struct(children...) 218 | } 219 | 220 | func mergeObjects(children []*parse.ObjectNode) *parse.ObjectNode { 221 | mergedChildren := make(map[string][]parse.Node) 222 | 223 | for _, object := range children { 224 | for varname, valueArray := range object.Children { 225 | if mergedChildren[varname] == nil { 226 | mergedChildren[varname] = valueArray 227 | } else { 228 | typeCount := countNodeTypes(mergedChildren[varname]) 229 | // We want to merge nested objects aswell. 230 | // For that, we need to check if 231 | // 1) the type for the values in mergedChildren is object 232 | // 2) the type for the values in valueArray is object 233 | if typeCount == 1 && 234 | mergedChildren[varname][0].Type() == parse.NodeTypeObject && 235 | valueArray[0].Type() == parse.NodeTypeObject { 236 | 237 | var objectsToBeMerged []*parse.ObjectNode 238 | objectsToBeMerged = append(objectsToBeMerged, castToObjectArr(mergedChildren[varname])...) 239 | objectsToBeMerged = append(objectsToBeMerged, castToObjectArr(valueArray)...) 240 | 241 | mergedObj := mergeObjects(objectsToBeMerged) 242 | 243 | mergedChildren[varname] = []parse.Node{mergedObj} 244 | } 245 | } 246 | } 247 | } 248 | 249 | return &parse.ObjectNode{ 250 | NodeType: parse.NodeTypeObject, 251 | Children: mergedChildren, 252 | } 253 | } 254 | 255 | func makeId(key string) *jen.Statement { 256 | return jen.Id(makeVarname(key)) 257 | } 258 | 259 | func makeVarname(key string) string { 260 | varnameRunes := stripInvalidCharacters([]rune(key)) 261 | varnameRunes = []rune(upperCaseFirstLetter(varnameRunes)) 262 | varname := string(varnameRunes) 263 | if identifierIsPredeclared(varname) { 264 | varname = "_" + varname 265 | } 266 | return varname 267 | } 268 | 269 | func upperCaseFirstLetter(characters []rune) []rune { 270 | transformedCharacters := make([]rune, len(characters)) 271 | copy(transformedCharacters, characters) 272 | for i, r := range []rune(transformedCharacters) { 273 | if unicode.IsLetter(r) { 274 | transformedCharacters[i] = unicode.ToUpper(r) 275 | return transformedCharacters 276 | } 277 | } 278 | return transformedCharacters 279 | } 280 | 281 | // Valid identifiers are specified here: https://go.dev/ref/spec#Identifiers. 282 | // Summarized we can say: 283 | // identifier = letter { letter | unicode_digit } . 284 | // letter = unicode_letter | "_" . 285 | // unicode_letter = /* a Unicode code point classified as "Letter" */ . 286 | // unicode_digit = /* a Unicode code point classified as "Number, decimal digit" */ . 287 | func stripInvalidCharacters(characters []rune) []rune { 288 | cleanedCharacters := make([]rune, len(characters)) 289 | copy(cleanedCharacters, characters) 290 | 291 | if !isLetter(cleanedCharacters[0]) { 292 | cleanedCharacters[0] = '_' 293 | } 294 | for i, char := range cleanedCharacters[1:] { 295 | if !(isLetter(char) || unicode.IsDigit(char)) { 296 | cleanedCharacters[i+1] = '_' 297 | } 298 | } 299 | return cleanedCharacters 300 | } 301 | 302 | func isLetter(letter rune) bool { 303 | return unicode.IsLetter(letter) || letter == '_' 304 | } 305 | 306 | var predeclaredIdentifiersMap = map[string]struct{}{ 307 | "any": {}, "bool": {}, "byte": {}, "comparable": {}, "complex64": {}, "complex128": {}, 308 | "error": {}, "float32": {}, "float64": {}, "int": {}, "int8": {}, "int16": {}, "int32": {}, 309 | "int64": {}, "rune": {}, "string": {}, "uint": {}, "uint8": {}, "uint16": {}, "uint32": {}, 310 | "uint64": {}, "uintptr": {}, "true": {}, "false": {}, "iota": {}, "nil": {}, "append": {}, 311 | "cap": {}, "close": {}, "complex": {}, "copy": {}, "delete": {}, "imag": {}, "len": {}, 312 | "make": {}, "new": {}, "panic": {}, "print": {}, "println": {}, "real": {}, "recover": {}, 313 | } 314 | 315 | func identifierIsPredeclared(identifier string) bool { 316 | _, ok := predeclaredIdentifiersMap[identifier] 317 | return ok 318 | } 319 | 320 | // addJSONTag adds the json-tag, e.g. `json:"title"`. This has to match the original varname from the json file 321 | func makeJSONTag(varname string) *jen.Statement { 322 | return jen.Tag(map[string]string{"json": varname}) 323 | } 324 | 325 | // Depending on `typ`, add the type of the identifier, e.g. `Title string`. 326 | func makePrimTypedef(typ parse.NodeType) *jen.Statement { 327 | switch typ { 328 | case parse.NodeTypeBool: 329 | return jen.Bool() 330 | case parse.NodeTypeNil: 331 | return jen.Interface() 332 | case parse.NodeTypeString: 333 | return jen.String() 334 | case parse.NodeTypeInteger: 335 | return jen.Int() 336 | case parse.NodeTypeFloat: 337 | return jen.Float64() 338 | default: 339 | panic("received unexpected primitive nodetype") 340 | } 341 | } 342 | 343 | func castToObjectArr(arr []parse.Node) []*parse.ObjectNode { 344 | objectArr := make([]*parse.ObjectNode, 0, len(arr)) 345 | for _, child := range arr { 346 | obj, ok := child.(*parse.ObjectNode) 347 | if !ok { 348 | panic("casting a node to objectnode failed") 349 | } 350 | objectArr = append(objectArr, obj) 351 | } 352 | return objectArr 353 | } 354 | 355 | func countNodeTypes(children []parse.Node) int { 356 | // If there are only zero or one children, then there are zero or one 357 | // different types of children aswell. 358 | childrenCount := len(children) 359 | if childrenCount <= 1 { 360 | return childrenCount 361 | } 362 | 363 | foundTypes := make(map[parse.NodeType]bool, 0) 364 | for _, child := range children { 365 | foundTypes[child.Type()] = true 366 | } 367 | return len(foundTypes) 368 | } 369 | -------------------------------------------------------------------------------- /pkg/generator/generator_test.go: -------------------------------------------------------------------------------- 1 | package generator 2 | 3 | import ( 4 | "go/format" 5 | "io/ioutil" 6 | "path" 7 | "strings" 8 | "testing" 9 | 10 | "github.com/kylelemons/godebug/diff" 11 | ) 12 | 13 | func Test_identifierIsValid(t *testing.T) { 14 | type args struct { 15 | varname string 16 | } 17 | tests := []struct { 18 | name string 19 | args args 20 | wantedCleanedIdentifier string 21 | }{ 22 | { 23 | name: "floating", 24 | args: args{"1.1"}, 25 | wantedCleanedIdentifier: "__1", 26 | }, 27 | { 28 | name: "negative floating", 29 | args: args{"-1.1"}, 30 | wantedCleanedIdentifier: "_1_1", 31 | }, 32 | { 33 | name: "int", 34 | args: args{"1"}, 35 | wantedCleanedIdentifier: "_", 36 | }, 37 | { 38 | name: "negative int", 39 | args: args{"-1"}, 40 | wantedCleanedIdentifier: "_1", 41 | }, 42 | { 43 | name: "leading $", 44 | args: args{"$test"}, 45 | wantedCleanedIdentifier: "_Test", 46 | }, 47 | { 48 | name: "only letters", 49 | args: args{"xyz"}, 50 | wantedCleanedIdentifier: "Xyz", 51 | }, 52 | { 53 | name: "underscore", 54 | args: args{"_test"}, 55 | wantedCleanedIdentifier: "_Test", 56 | }, 57 | { 58 | name: "invalid character in the middle", 59 | args: args{"__test"}, 60 | wantedCleanedIdentifier: "__Test", 61 | }, 62 | { 63 | name: "-", 64 | args: args{"content-type"}, 65 | wantedCleanedIdentifier: "Content_type", 66 | }, 67 | { 68 | name: "camelCase", 69 | args: args{"camelCase"}, 70 | wantedCleanedIdentifier: "CamelCase", 71 | }, 72 | { 73 | name: "snake_case", 74 | args: args{"snake_case"}, 75 | wantedCleanedIdentifier: "Snake_case", 76 | }, 77 | } 78 | for _, tt := range tests { 79 | t.Run(tt.name, func(t *testing.T) { 80 | if got := makeVarname(tt.args.varname); got != tt.wantedCleanedIdentifier { 81 | t.Errorf("stripInvalidCharacters() = %v, want %v", got, tt.wantedCleanedIdentifier) 82 | } 83 | }) 84 | } 85 | } 86 | 87 | const dirName = "testdata" 88 | const expectedSuffix = "_expected" 89 | 90 | func TestFiles(t *testing.T) { 91 | inputFiles, err := listValidInputFiles() 92 | if err != nil { 93 | t.Fatal("Error reading input files", err) 94 | } 95 | 96 | for _, filename := range inputFiles { 97 | 98 | input := readFile(filename) 99 | expected := readFile(filename + expectedSuffix) 100 | actual, err := GenerateOutputFromString(input) 101 | if err != nil { 102 | t.Errorf("Test resulted in error. Filename: %v, Error: %v", filename, err) 103 | } 104 | 105 | formatExpectedBytes, _ := format.Source([]byte(expected)) 106 | formatActualBytes, _ := format.Source([]byte(actual)) 107 | 108 | expected = string(formatExpectedBytes) 109 | actual = string(formatActualBytes) 110 | 111 | if actual != expected { 112 | t.Errorf("Test failed. \nFilename: %v \nDiff: \n\n%v", filename, diff.Diff(actual, expected)) 113 | } 114 | } 115 | } 116 | 117 | func BenchmarkLargeFile(b *testing.B) { 118 | largeFile := readFile("./testdata/big_reddit_response") 119 | 120 | for i := 0; i < b.N; i++ { 121 | _, err := GenerateOutputFromString(largeFile) 122 | if err != nil { 123 | b.Fatal("Error generating output", err) 124 | } 125 | } 126 | } 127 | 128 | func listValidInputFiles() ([]string, error) { 129 | dirFiles, err := ioutil.ReadDir(dirName) 130 | if err != nil { 131 | return nil, err 132 | } 133 | 134 | var inputFiles []string 135 | inputFileHasExpectedFile := make(map[string]bool, 2) 136 | 137 | for _, f := range dirFiles { 138 | fileName := f.Name() 139 | isExpectedFile := strings.HasSuffix(fileName, expectedSuffix) 140 | if isExpectedFile { 141 | inputFileNameLength := strings.Index(fileName, expectedSuffix) 142 | inputFileName := fileName[:inputFileNameLength] 143 | inputFileHasExpectedFile[inputFileName] = true 144 | } else { 145 | inputFiles = append(inputFiles, fileName) 146 | } 147 | } 148 | 149 | var validInputFiles []string 150 | for _, f := range inputFiles { 151 | if inputFileHasExpectedFile[f] { 152 | validInputFiles = append(validInputFiles, path.Join(dirName, f)) 153 | } 154 | } 155 | return validInputFiles, nil 156 | } 157 | 158 | func readFile(filename string) string { 159 | content, err := ioutil.ReadFile(filename) 160 | if err != nil { 161 | panic("error reading file " + filename) 162 | } 163 | return string(content) 164 | } 165 | -------------------------------------------------------------------------------- /pkg/generator/testdata/1: -------------------------------------------------------------------------------- 1 | { 2 | "glossary": { 3 | "title": "example glossary", 4 | "GlossDiv": { 5 | "title": "S", 6 | "GlossList": { 7 | "GlossEntry": { 8 | "ID": "SGML", 9 | "SortAs": "SGML", 10 | "GlossTerm": "Standard Generalized Markup Language", 11 | "Acronym": "SGML", 12 | "Abbrev": "ISO 8879:1986", 13 | "GlossDef": { 14 | "para": "A meta-markup language, used to create markup languages such as DocBook.", 15 | "GlossSeeAlso": [ 16 | "GML", 17 | "XML" 18 | ] 19 | }, 20 | "GlossSee": "markup" 21 | } 22 | } 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /pkg/generator/testdata/10: -------------------------------------------------------------------------------- 1 | [ 2 | [ 3 | "test", "hi" 4 | ] 5 | ] -------------------------------------------------------------------------------- /pkg/generator/testdata/10_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []interface{} -------------------------------------------------------------------------------- /pkg/generator/testdata/11: -------------------------------------------------------------------------------- 1 | { "1234": "whatever" } -------------------------------------------------------------------------------- /pkg/generator/testdata/11_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct struct { 4 | _234 string `json:"1234"` 5 | } 6 | -------------------------------------------------------------------------------- /pkg/generator/testdata/1_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct struct { 4 | Glossary struct { 5 | GlossDiv struct { 6 | GlossList struct { 7 | GlossEntry struct { 8 | Abbrev string `json:"Abbrev"` 9 | Acronym string `json:"Acronym"` 10 | GlossDef struct { 11 | GlossSeeAlso []string `json:"GlossSeeAlso"` 12 | Para string `json:"para"` 13 | } `json:"GlossDef"` 14 | GlossSee string `json:"GlossSee"` 15 | GlossTerm string `json:"GlossTerm"` 16 | ID string `json:"ID"` 17 | SortAs string `json:"SortAs"` 18 | } `json:"GlossEntry"` 19 | } `json:"GlossList"` 20 | Title string `json:"title"` 21 | } `json:"GlossDiv"` 22 | Title string `json:"title"` 23 | } `json:"glossary"` 24 | } 25 | -------------------------------------------------------------------------------- /pkg/generator/testdata/2: -------------------------------------------------------------------------------- 1 | { 2 | "src": "Images/Sun.png", 3 | "name": "sun1", 4 | "hOffset": 250, 5 | "vOffset": 250, 6 | "alignment": "center", 7 | "visible": true 8 | } -------------------------------------------------------------------------------- /pkg/generator/testdata/2_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct struct { 4 | Alignment string `json:"alignment"` 5 | HOffset int `json:"hOffset"` 6 | Name string `json:"name"` 7 | Src string `json:"src"` 8 | VOffset int `json:"vOffset"` 9 | Visible bool `json:"visible"` 10 | } 11 | -------------------------------------------------------------------------------- /pkg/generator/testdata/3: -------------------------------------------------------------------------------- 1 | { 2 | "Testobj": { 3 | "Teststring": "Hey" 4 | }, 5 | "Testobj": { 6 | "Testbool": true 7 | } 8 | } -------------------------------------------------------------------------------- /pkg/generator/testdata/3_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct struct { 4 | Testobj struct { 5 | Testbool bool `json:"Testbool"` 6 | Teststring string `json:"Teststring"` 7 | } `json:"Testobj"` 8 | } 9 | -------------------------------------------------------------------------------- /pkg/generator/testdata/4: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "teststring": "Hey" 4 | }, 5 | { 6 | "testbool": true 7 | } 8 | ] -------------------------------------------------------------------------------- /pkg/generator/testdata/4_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []struct { 4 | Testbool bool `json:"testbool"` 5 | Teststring string `json:"teststring"` 6 | } 7 | -------------------------------------------------------------------------------- /pkg/generator/testdata/5: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "thissucks": true 4 | }, 5 | { 6 | "thisdoesntsuck": { 7 | "value": false 8 | } 9 | } 10 | ] -------------------------------------------------------------------------------- /pkg/generator/testdata/5_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []struct { 4 | Thisdoesntsuck struct { 5 | Value bool `json:"value"` 6 | } `json:"thisdoesntsuck"` 7 | Thissucks bool `json:"thissucks"` 8 | } 9 | -------------------------------------------------------------------------------- /pkg/generator/testdata/6: -------------------------------------------------------------------------------- 1 | { 2 | "NestedObj": { 3 | "Testbool": true 4 | } 5 | } -------------------------------------------------------------------------------- /pkg/generator/testdata/6_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct struct { 4 | NestedObj struct { 5 | Testbool bool `json:"Testbool"` 6 | } `json:"NestedObj"` 7 | } 8 | -------------------------------------------------------------------------------- /pkg/generator/testdata/7: -------------------------------------------------------------------------------- 1 | { 2 | "Testfloat": 56.7, 3 | "Testint": 56 4 | } -------------------------------------------------------------------------------- /pkg/generator/testdata/7_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct struct { 4 | Testfloat float64 `json:"Testfloat"` 5 | Testint int `json:"Testint"` 6 | } 7 | -------------------------------------------------------------------------------- /pkg/generator/testdata/8: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /pkg/generator/testdata/8_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct struct{} 4 | -------------------------------------------------------------------------------- /pkg/generator/testdata/9: -------------------------------------------------------------------------------- 1 | [ "hi", true ] -------------------------------------------------------------------------------- /pkg/generator/testdata/9_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []interface{} -------------------------------------------------------------------------------- /pkg/generator/testdata/big_reddit_response_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []struct { 4 | Data struct { 5 | After interface{} `json:"after"` 6 | Before interface{} `json:"before"` 7 | Children []struct { 8 | Data struct { 9 | All_awardings []interface{} `json:"all_awardings"` 10 | Allow_live_comments bool `json:"allow_live_comments"` 11 | Approved_at_utc interface{} `json:"approved_at_utc"` 12 | Approved_by interface{} `json:"approved_by"` 13 | Archived bool `json:"archived"` 14 | Author string `json:"author"` 15 | Author_flair_background_color interface{} `json:"author_flair_background_color"` 16 | Author_flair_css_class string `json:"author_flair_css_class"` 17 | Author_flair_richtext []interface{} `json:"author_flair_richtext"` 18 | Author_flair_template_id string `json:"author_flair_template_id"` 19 | Author_flair_text string `json:"author_flair_text"` 20 | Author_flair_text_color string `json:"author_flair_text_color"` 21 | Author_flair_type string `json:"author_flair_type"` 22 | Author_fullname string `json:"author_fullname"` 23 | Author_patreon_flair bool `json:"author_patreon_flair"` 24 | Banned_at_utc interface{} `json:"banned_at_utc"` 25 | Banned_by interface{} `json:"banned_by"` 26 | Can_gild bool `json:"can_gild"` 27 | Can_mod_post bool `json:"can_mod_post"` 28 | Category interface{} `json:"category"` 29 | Clicked bool `json:"clicked"` 30 | Content_categories interface{} `json:"content_categories"` 31 | Contest_mode bool `json:"contest_mode"` 32 | Created float64 `json:"created"` 33 | Created_utc float64 `json:"created_utc"` 34 | Discussion_type interface{} `json:"discussion_type"` 35 | Distinguished interface{} `json:"distinguished"` 36 | Domain string `json:"domain"` 37 | Downs int `json:"downs"` 38 | Edited float64 `json:"edited"` 39 | Gilded int `json:"gilded"` 40 | Gildings struct{} `json:"gildings"` 41 | Hidden bool `json:"hidden"` 42 | Hide_score bool `json:"hide_score"` 43 | Id string `json:"id"` 44 | Is_crosspostable bool `json:"is_crosspostable"` 45 | Is_meta bool `json:"is_meta"` 46 | Is_original_content bool `json:"is_original_content"` 47 | Is_reddit_media_domain bool `json:"is_reddit_media_domain"` 48 | Is_robot_indexable bool `json:"is_robot_indexable"` 49 | Is_self bool `json:"is_self"` 50 | Is_video bool `json:"is_video"` 51 | Likes interface{} `json:"likes"` 52 | Link_flair_background_color string `json:"link_flair_background_color"` 53 | Link_flair_css_class interface{} `json:"link_flair_css_class"` 54 | Link_flair_richtext []interface{} `json:"link_flair_richtext"` 55 | Link_flair_text interface{} `json:"link_flair_text"` 56 | Link_flair_text_color string `json:"link_flair_text_color"` 57 | Link_flair_type string `json:"link_flair_type"` 58 | Locked bool `json:"locked"` 59 | Media interface{} `json:"media"` 60 | Media_embed struct{} `json:"media_embed"` 61 | Media_only bool `json:"media_only"` 62 | Mod_note interface{} `json:"mod_note"` 63 | Mod_reason_by interface{} `json:"mod_reason_by"` 64 | Mod_reason_title interface{} `json:"mod_reason_title"` 65 | Mod_reports []interface{} `json:"mod_reports"` 66 | Name string `json:"name"` 67 | No_follow bool `json:"no_follow"` 68 | Num_comments int `json:"num_comments"` 69 | Num_crossposts int `json:"num_crossposts"` 70 | Num_duplicates int `json:"num_duplicates"` 71 | Num_reports interface{} `json:"num_reports"` 72 | Over_18 bool `json:"over_18"` 73 | Parent_whitelist_status string `json:"parent_whitelist_status"` 74 | Permalink string `json:"permalink"` 75 | Pinned bool `json:"pinned"` 76 | Pwls int `json:"pwls"` 77 | Quarantine bool `json:"quarantine"` 78 | Removal_reason interface{} `json:"removal_reason"` 79 | Report_reasons interface{} `json:"report_reasons"` 80 | Saved bool `json:"saved"` 81 | Score int `json:"score"` 82 | Secure_media interface{} `json:"secure_media"` 83 | Secure_media_embed struct{} `json:"secure_media_embed"` 84 | Selftext string `json:"selftext"` 85 | Selftext_html string `json:"selftext_html"` 86 | Send_replies bool `json:"send_replies"` 87 | Spoiler bool `json:"spoiler"` 88 | Stickied bool `json:"stickied"` 89 | Subreddit string `json:"subreddit"` 90 | Subreddit_id string `json:"subreddit_id"` 91 | Subreddit_name_prefixed string `json:"subreddit_name_prefixed"` 92 | Subreddit_subscribers int `json:"subreddit_subscribers"` 93 | Subreddit_type string `json:"subreddit_type"` 94 | Suggested_sort interface{} `json:"suggested_sort"` 95 | Thumbnail string `json:"thumbnail"` 96 | Title string `json:"title"` 97 | Total_awards_received int `json:"total_awards_received"` 98 | Ups int `json:"ups"` 99 | Upvote_ratio float64 `json:"upvote_ratio"` 100 | Url string `json:"url"` 101 | User_reports []interface{} `json:"user_reports"` 102 | View_count interface{} `json:"view_count"` 103 | Visited bool `json:"visited"` 104 | Whitelist_status string `json:"whitelist_status"` 105 | Wls int `json:"wls"` 106 | } `json:"data"` 107 | Kind string `json:"kind"` 108 | } `json:"children"` 109 | Dist int `json:"dist"` 110 | Modhash string `json:"modhash"` 111 | } `json:"data"` 112 | Kind string `json:"kind"` 113 | } 114 | -------------------------------------------------------------------------------- /pkg/generator/testdata/nested_equal_objects_in_array: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "data": { 4 | "teststring": "hi" 5 | } 6 | }, 7 | { 8 | "data": { 9 | "testbool": true 10 | } 11 | } 12 | ] -------------------------------------------------------------------------------- /pkg/generator/testdata/nested_equal_objects_in_array_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []struct { 4 | Data struct { 5 | Testbool bool `json:"testbool"` 6 | Teststring string `json:"teststring"` 7 | } `json:"data"` 8 | } 9 | -------------------------------------------------------------------------------- /pkg/generator/testdata/number_1.0: -------------------------------------------------------------------------------- 1 | [1.0] -------------------------------------------------------------------------------- /pkg/generator/testdata/number_1.000000000000000005: -------------------------------------------------------------------------------- 1 | [1.000000000000000005] -------------------------------------------------------------------------------- /pkg/generator/testdata/number_1.000000000000000005_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []float64 -------------------------------------------------------------------------------- /pkg/generator/testdata/number_1.0_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []float64 -------------------------------------------------------------------------------- /pkg/generator/testdata/number_1000000000000000: -------------------------------------------------------------------------------- 1 | [1000000000000000] 2 | -------------------------------------------------------------------------------- /pkg/generator/testdata/number_10000000000000000999: -------------------------------------------------------------------------------- 1 | [10000000000000000999] -------------------------------------------------------------------------------- /pkg/generator/testdata/number_10000000000000000999_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []int -------------------------------------------------------------------------------- /pkg/generator/testdata/number_1000000000000000_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []int 4 | -------------------------------------------------------------------------------- /pkg/generator/testdata/number_1e-999: -------------------------------------------------------------------------------- 1 | [1E-999] -------------------------------------------------------------------------------- /pkg/generator/testdata/number_1e-999_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []float64 -------------------------------------------------------------------------------- /pkg/generator/testdata/number_1e6: -------------------------------------------------------------------------------- 1 | [1E6] -------------------------------------------------------------------------------- /pkg/generator/testdata/number_1e6_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []float64 -------------------------------------------------------------------------------- /pkg/generator/testdata/object_same_key_same_value: -------------------------------------------------------------------------------- 1 | {"a":1,"a":1} -------------------------------------------------------------------------------- /pkg/generator/testdata/object_same_key_same_value_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct struct { 4 | A int `json:"a"` 5 | } -------------------------------------------------------------------------------- /pkg/generator/testdata/object_same_key_unclear_values: -------------------------------------------------------------------------------- 1 | {"a":0, "a":-0} 2 | -------------------------------------------------------------------------------- /pkg/generator/testdata/object_same_key_unclear_values_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct struct { 4 | A int `json:"a"` 5 | } -------------------------------------------------------------------------------- /pkg/generator/testdata/string_1_escaped_invalid_codepoint: -------------------------------------------------------------------------------- 1 | ["\uD800"] -------------------------------------------------------------------------------- /pkg/generator/testdata/string_1_escaped_invalid_codepoint_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []string -------------------------------------------------------------------------------- /pkg/generator/testdata/string_1_invalid_codepoint: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marhaupe/json2struct/90935814bea2f385e06714a5f07de95ba4e70451/pkg/generator/testdata/string_1_invalid_codepoint -------------------------------------------------------------------------------- /pkg/generator/testdata/string_1_invalid_codepoint_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []string -------------------------------------------------------------------------------- /pkg/generator/testdata/string_2_escaped_invalid_codepoints: -------------------------------------------------------------------------------- 1 | ["\uD800\uD800"] -------------------------------------------------------------------------------- /pkg/generator/testdata/string_2_escaped_invalid_codepoints_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []string -------------------------------------------------------------------------------- /pkg/generator/testdata/string_2_invalid_codepoints: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marhaupe/json2struct/90935814bea2f385e06714a5f07de95ba4e70451/pkg/generator/testdata/string_2_invalid_codepoints -------------------------------------------------------------------------------- /pkg/generator/testdata/string_2_invalid_codepoints_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []string -------------------------------------------------------------------------------- /pkg/generator/testdata/string_3_escaped_invalid_codepoints: -------------------------------------------------------------------------------- 1 | ["\uD800\uD800\uD800"] -------------------------------------------------------------------------------- /pkg/generator/testdata/string_3_escaped_invalid_codepoints_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []string -------------------------------------------------------------------------------- /pkg/generator/testdata/string_3_invalid_codepoints: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marhaupe/json2struct/90935814bea2f385e06714a5f07de95ba4e70451/pkg/generator/testdata/string_3_invalid_codepoints -------------------------------------------------------------------------------- /pkg/generator/testdata/string_3_invalid_codepoints_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []string -------------------------------------------------------------------------------- /pkg/generator/testdata/string_with_escaped_NULL: -------------------------------------------------------------------------------- 1 | ["A\u0000B"] -------------------------------------------------------------------------------- /pkg/generator/testdata/string_with_escaped_NULL_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct []string -------------------------------------------------------------------------------- /pkg/generator/testdata/with_invalid_characters: -------------------------------------------------------------------------------- 1 | { 2 | "content-type": "application/vnd.microsoft.card.adaptive", 3 | "content": { 4 | "type": "AdaptiveCard", 5 | "body": [ 6 | { 7 | "type": "TextBlock", 8 | "text": "Hi John Doe" 9 | } 10 | ], 11 | "$schema": "https://adaptivecards.io/schemas/adaptive-card.json", 12 | "version": "1.0", 13 | "msteams": { 14 | "entities": [ 15 | { 16 | "type": "mention", 17 | "text": "John Doe", 18 | "mentioned": { 19 | "id": "29:123124124124", 20 | "name": "John Doe" 21 | } 22 | } 23 | ] 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /pkg/generator/testdata/with_invalid_characters_expected: -------------------------------------------------------------------------------- 1 | package generated 2 | 3 | type JSONToStruct struct { 4 | Content struct { 5 | _Schema string `json:"$schema"` 6 | Body []struct { 7 | Text string `json:"text"` 8 | Type string `json:"type"` 9 | } `json:"body"` 10 | Msteams struct { 11 | Entities []struct { 12 | Mentioned struct { 13 | Id string `json:"id"` 14 | Name string `json:"name"` 15 | } `json:"mentioned"` 16 | Text string `json:"text"` 17 | Type string `json:"type"` 18 | } `json:"entities"` 19 | } `json:"msteams"` 20 | Type string `json:"type"` 21 | Version string `json:"version"` 22 | } `json:"content"` 23 | Content_type string `json:"content-type"` 24 | } 25 | -------------------------------------------------------------------------------- /pkg/lex/lexer.go: -------------------------------------------------------------------------------- 1 | package lex 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "unicode/utf8" 7 | ) 8 | 9 | type Item struct { 10 | Typ ItemType 11 | Pos int 12 | Value string 13 | } 14 | 15 | type ItemType int 16 | 17 | const ( 18 | ItemString ItemType = iota 19 | ItemBool 20 | ItemInteger 21 | ItemFloat 22 | ItemNil 23 | ItemLeftBrace 24 | ItemRightBrace 25 | ItemLeftSqrBrace 26 | ItemRightSqrBrace 27 | ItemComma 28 | ItemColon 29 | ItemEOF 30 | ItemError 31 | ) 32 | 33 | const ( 34 | whitespace = ' ' 35 | tab = '\t' 36 | newline = '\n' 37 | comma = ',' 38 | colon = ':' 39 | leftBrace = '{' 40 | rightBrace = '}' 41 | leftSqrBrace = '[' 42 | rightSqrBrace = ']' 43 | quote = '"' 44 | plus = '+' 45 | minus = '-' 46 | zero = '0' 47 | nine = '9' 48 | n = 'n' 49 | t = 't' 50 | f = 'f' 51 | backslash = '\\' 52 | validNumberPrefixes = "+-" 53 | validNumberDigits = "0123456789" 54 | validNumberSuffixes = ".eE+-0123456789" 55 | wordTrue = "true" 56 | wordFalse = "false" 57 | wordNullLength = len("null") 58 | ) 59 | 60 | const EOF = -1 61 | 62 | type Lexer struct { 63 | input string 64 | pos int 65 | start int 66 | width int 67 | state stateFn 68 | } 69 | 70 | func (l *Lexer) NextItem() *Item { 71 | for { 72 | newState, item := l.state(l) 73 | l.state = newState 74 | if item != nil { 75 | return item 76 | } 77 | } 78 | } 79 | 80 | func Lex(json string) *Lexer { 81 | l := &Lexer{ 82 | input: json, 83 | pos: 0, 84 | start: 0, 85 | width: 0, 86 | state: lexWhitespace, 87 | } 88 | return l 89 | } 90 | 91 | func (l *Lexer) next() rune { 92 | if l.pos >= len(l.input) { 93 | l.width = 0 94 | return EOF 95 | } 96 | // ASCII fast path 97 | r := l.input[l.pos] 98 | if r < utf8.RuneSelf { 99 | l.width = 1 100 | l.pos++ 101 | return rune(r) 102 | } 103 | // Slow path for multi-byte runes 104 | rn, width := utf8.DecodeRuneInString(l.input[l.pos:]) 105 | l.width = width 106 | l.pos += l.width 107 | return rn 108 | } 109 | 110 | func (l *Lexer) acceptRun(valid string) int { 111 | validCount := 0 112 | for strings.ContainsRune(valid, l.next()) { 113 | validCount++ 114 | } 115 | l.backup() 116 | return validCount 117 | } 118 | 119 | func (l *Lexer) backup() { 120 | l.pos -= l.width 121 | } 122 | 123 | func (l *Lexer) emit(t ItemType) *Item { 124 | item := &Item{ 125 | Typ: t, 126 | Pos: l.pos, 127 | Value: l.input[l.start:l.pos], 128 | } 129 | l.start = l.pos 130 | return item 131 | } 132 | 133 | func (l *Lexer) emitError(msg string) *Item { 134 | item := &Item{ 135 | Typ: ItemError, 136 | Pos: l.pos, 137 | Value: msg, 138 | } 139 | l.start = l.pos 140 | return item 141 | } 142 | 143 | func (l *Lexer) ignore() { 144 | l.start = l.pos 145 | } 146 | 147 | // func (l *Lexer) run() { 148 | // defer func() { 149 | // if r := recover(); r != nil { 150 | // l.emitError(fmt.Sprint(r)) 151 | // } 152 | // }() 153 | 154 | // for state := lexWhitespace; state != nil; { 155 | // state = state(l) 156 | // } 157 | // defer close(l.items) 158 | // } 159 | 160 | type stateFn func(l *Lexer) (stateFn, *Item) 161 | 162 | func lexWhitespace(l *Lexer) (stateFn, *Item) { 163 | for r := l.next(); isSpace(r) || r == newline; r = l.next() { 164 | } 165 | l.backup() 166 | l.ignore() 167 | 168 | switch r := l.next(); { 169 | case r == EOF: 170 | item := l.emit(ItemEOF) 171 | return nil, item 172 | case r == leftBrace: 173 | return lexLeftBrace, nil 174 | case r == leftSqrBrace: 175 | return lexLeftSqrBrace, nil 176 | case r == rightBrace: 177 | return lexRightBrace, nil 178 | case r == rightSqrBrace: 179 | return lexRightSqrBrace, nil 180 | case r == colon: 181 | return lexColon, nil 182 | case r == comma: 183 | return lexComma, nil 184 | case r == quote: 185 | return lexString, nil 186 | case isNumber(r): 187 | l.backup() 188 | return lexNumber, nil 189 | case isNull(r): 190 | l.backup() 191 | return lexNull, nil 192 | case isBool(r): 193 | l.backup() 194 | return lexBool, nil 195 | default: 196 | panic(fmt.Sprintf("unexpected character %v", string(r))) 197 | } 198 | } 199 | 200 | func lexNull(l *Lexer) (stateFn, *Item) { 201 | l.pos += wordNullLength 202 | item := l.emit(ItemNil) 203 | return lexWhitespace, item 204 | } 205 | 206 | func lexBool(l *Lexer) (stateFn, *Item) { 207 | var item *Item 208 | for { 209 | r := l.next() 210 | if r == EOF { 211 | panic("unexpected eof while lexing bool") 212 | } 213 | word := l.input[l.start:l.pos] 214 | if word == wordTrue || word == wordFalse { 215 | item = l.emit(ItemBool) 216 | break 217 | } 218 | } 219 | return lexWhitespace, item 220 | } 221 | 222 | func lexNumber(l *Lexer) (stateFn, *Item) { 223 | l.acceptRun(validNumberPrefixes) 224 | l.acceptRun(validNumberDigits) 225 | 226 | count := l.acceptRun(validNumberSuffixes) 227 | var item *Item 228 | if count > 0 { 229 | item = l.emit(ItemFloat) 230 | } else { 231 | item = l.emit(ItemInteger) 232 | } 233 | 234 | return lexWhitespace, item 235 | } 236 | 237 | func lexString(l *Lexer) (stateFn, *Item) { 238 | // the current rune is known to be `"`. Throw it away in order to emit the raw string value 239 | // e.g. example instead of "example". 240 | l.ignore() 241 | for r := l.next(); r != quote; r = l.next() { 242 | if r == backslash { 243 | r = l.next() 244 | } 245 | if r == EOF { 246 | panic("unterminated string") 247 | } 248 | } 249 | 250 | // the current rune is the closing `"`. Throw this one away as well by decrementing the position. Reset the correct state after emitting the lexem. 251 | l.pos-- 252 | item := l.emit(ItemString) 253 | l.pos++ 254 | return lexWhitespace, item 255 | } 256 | 257 | func lexComma(l *Lexer) (stateFn, *Item) { 258 | item := l.emit(ItemComma) 259 | return lexWhitespace, item 260 | } 261 | 262 | func lexColon(l *Lexer) (stateFn, *Item) { 263 | item := l.emit(ItemColon) 264 | return lexWhitespace, item 265 | } 266 | 267 | func lexLeftBrace(l *Lexer) (stateFn, *Item) { 268 | item := l.emit(ItemLeftBrace) 269 | return lexWhitespace, item 270 | } 271 | 272 | func lexRightBrace(l *Lexer) (stateFn, *Item) { 273 | item := l.emit(ItemRightBrace) 274 | return lexWhitespace, item 275 | } 276 | 277 | func lexLeftSqrBrace(l *Lexer) (stateFn, *Item) { 278 | item := l.emit(ItemLeftSqrBrace) 279 | return lexWhitespace, item 280 | } 281 | 282 | func lexRightSqrBrace(l *Lexer) (stateFn, *Item) { 283 | item := l.emit(ItemRightSqrBrace) 284 | return lexWhitespace, item 285 | } 286 | 287 | const () 288 | 289 | func isSpace(r rune) bool { 290 | return r == whitespace || r == tab 291 | } 292 | 293 | func isNumber(r rune) bool { 294 | return r == plus || r == minus || (zero <= r && r <= nine) 295 | } 296 | 297 | func isNull(r rune) bool { 298 | return r == n 299 | } 300 | 301 | func isBool(r rune) bool { 302 | return r == t || r == f 303 | } 304 | -------------------------------------------------------------------------------- /pkg/lex/lexer_test.go: -------------------------------------------------------------------------------- 1 | package lex 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | type lexTest struct { 8 | name string 9 | input string 10 | items []*Item 11 | } 12 | 13 | func mkItem(typ ItemType, text string) *Item { 14 | return &Item{ 15 | Typ: typ, 16 | Value: text, 17 | } 18 | } 19 | 20 | var ( 21 | iLeftBrace = mkItem(ItemLeftBrace, "{") 22 | iRightBrace = mkItem(ItemRightBrace, "}") 23 | iLeftSqrBrace = mkItem(ItemLeftSqrBrace, "[") 24 | iRightSqrBrace = mkItem(ItemRightSqrBrace, "]") 25 | iEOF = mkItem(ItemEOF, "") 26 | iColon = mkItem(ItemColon, ":") 27 | iComma = mkItem(ItemComma, ",") 28 | ) 29 | 30 | // collect gathers the emitted items into a slice. 31 | func collect(t *lexTest) (items []*Item) { 32 | l := Lex(t.input) 33 | for { 34 | item := l.NextItem() 35 | items = append(items, item) 36 | if item.Typ == ItemEOF { 37 | break 38 | } 39 | } 40 | return items 41 | } 42 | 43 | func equal(i1, i2 []*Item, checkPos bool) bool { 44 | if len(i1) != len(i2) { 45 | return false 46 | } 47 | for k := range i1 { 48 | if i1[k].Typ != i2[k].Typ { 49 | return false 50 | } 51 | if i1[k].Value != i2[k].Value { 52 | return false 53 | } 54 | if checkPos && i1[k].Pos != i2[k].Pos { 55 | return false 56 | } 57 | } 58 | return true 59 | } 60 | 61 | var lexTests = []lexTest{ 62 | {"empty file", "", []*Item{iEOF}}, 63 | {"empty object root", "{}", []*Item{ 64 | iLeftBrace, 65 | iRightBrace, 66 | iEOF, 67 | }}, 68 | {"bools in object root", `{ 69 | "bool1": true, 70 | "bool2": false 71 | }`, []*Item{ 72 | iLeftBrace, 73 | mkItem(ItemString, "bool1"), 74 | iColon, 75 | mkItem(ItemBool, "true"), 76 | iComma, 77 | mkItem(ItemString, "bool2"), 78 | iColon, 79 | mkItem(ItemBool, "false"), 80 | iRightBrace, 81 | iEOF, 82 | }}, 83 | {"valid numbers in object root", `{ 84 | "number1": 1, 85 | "number2": 1.0, 86 | "number3": -1, 87 | "number4": -1.0 88 | }`, []*Item{ 89 | iLeftBrace, 90 | mkItem(ItemString, "number1"), 91 | iColon, 92 | mkItem(ItemInteger, "1"), 93 | iComma, 94 | mkItem(ItemString, "number2"), 95 | iColon, 96 | mkItem(ItemFloat, "1.0"), 97 | iComma, 98 | mkItem(ItemString, "number3"), 99 | iColon, 100 | mkItem(ItemInteger, "-1"), 101 | iComma, 102 | mkItem(ItemString, "number4"), 103 | iColon, 104 | mkItem(ItemFloat, "-1.0"), 105 | iRightBrace, 106 | iEOF, 107 | }}, 108 | {"valid strings in object root", `{ 109 | "string1": "value1", 110 | "string2": "true", 111 | "string3": "false", 112 | "string4": "null", 113 | "string5": "1", 114 | "string6": "blabla \"xyz\"" 115 | }`, []*Item{ 116 | iLeftBrace, 117 | mkItem(ItemString, "string1"), 118 | iColon, 119 | mkItem(ItemString, "value1"), 120 | iComma, 121 | mkItem(ItemString, "string2"), 122 | iColon, 123 | mkItem(ItemString, "true"), 124 | iComma, 125 | mkItem(ItemString, "string3"), 126 | iColon, 127 | mkItem(ItemString, "false"), 128 | iComma, 129 | mkItem(ItemString, "string4"), 130 | iColon, 131 | mkItem(ItemString, "null"), 132 | iComma, 133 | mkItem(ItemString, "string5"), 134 | iColon, 135 | mkItem(ItemString, "1"), 136 | iComma, 137 | mkItem(ItemString, "string6"), 138 | iColon, 139 | mkItem(ItemString, "blabla \\\"xyz\\\""), 140 | iRightBrace, 141 | iEOF, 142 | }}, 143 | {"null in object root", `{ "null1": null }`, []*Item{ 144 | iLeftBrace, 145 | mkItem(ItemString, "null1"), 146 | iColon, 147 | mkItem(ItemNil, "null"), 148 | iRightBrace, 149 | iEOF, 150 | }}, 151 | {"nested objects with multiple keys and values", ` 152 | { 153 | "obj1": { 154 | "null1": null, 155 | "bool1": true 156 | } 157 | }`, []*Item{ 158 | iLeftBrace, 159 | mkItem(ItemString, "obj1"), 160 | iColon, 161 | iLeftBrace, 162 | mkItem(ItemString, "null1"), 163 | iColon, 164 | mkItem(ItemNil, "null"), 165 | iComma, 166 | mkItem(ItemString, "bool1"), 167 | iColon, 168 | mkItem(ItemBool, "true"), 169 | iRightBrace, 170 | iRightBrace, 171 | iEOF, 172 | }}, 173 | {"empty array root", "[]", []*Item{ 174 | iLeftSqrBrace, 175 | iRightSqrBrace, 176 | iEOF, 177 | }}, 178 | {"bools in array root", `[ true, false, false, true ]`, []*Item{ 179 | iLeftSqrBrace, 180 | mkItem(ItemBool, "true"), 181 | iComma, 182 | mkItem(ItemBool, "false"), 183 | iComma, 184 | mkItem(ItemBool, "false"), 185 | iComma, 186 | mkItem(ItemBool, "true"), 187 | iRightSqrBrace, 188 | iEOF, 189 | }}, 190 | } 191 | 192 | func TestLex(t *testing.T) { 193 | for _, test := range lexTests { 194 | items := collect(&test) 195 | if !equal(items, test.items, false) { 196 | t.Errorf("%s: got\n\t%+v\nexpected\n\t%v", test.name, items, test.items) 197 | } 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /pkg/parse/parser.go: -------------------------------------------------------------------------------- 1 | package parse 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | 7 | "github.com/marhaupe/json2struct/pkg/lex" 8 | ) 9 | 10 | type Parser struct { 11 | Lexer *lex.Lexer 12 | Item *lex.Item 13 | LastItem *lex.Item 14 | } 15 | 16 | type Node interface { 17 | Type() NodeType 18 | } 19 | 20 | type NodeType int 21 | 22 | func (t NodeType) Type() NodeType { 23 | return t 24 | } 25 | 26 | const ( 27 | NodeTypeArray NodeType = iota 28 | NodeTypeObject 29 | NodeTypeString 30 | NodeTypeBool 31 | NodeTypeNil 32 | NodeTypeFloat 33 | NodeTypeInteger 34 | ) 35 | 36 | type ArrayNode struct { 37 | NodeType 38 | Children []Node 39 | } 40 | 41 | type ObjectNode struct { 42 | NodeType 43 | // The JSON spec allows different types of values for the same key. Because of that, a simple `map[string]Node` is not enough. 44 | Children map[string][]Node 45 | } 46 | 47 | type PrimitiveNode struct { 48 | NodeType 49 | } 50 | 51 | // Singleton primitive nodes to avoid allocations 52 | var ( 53 | stringNode = &PrimitiveNode{NodeType: NodeTypeString} 54 | boolNode = &PrimitiveNode{NodeType: NodeTypeBool} 55 | nilNode = &PrimitiveNode{NodeType: NodeTypeNil} 56 | floatNode = &PrimitiveNode{NodeType: NodeTypeFloat} 57 | integerNode = &PrimitiveNode{NodeType: NodeTypeInteger} 58 | ) 59 | 60 | func ParseFromString(j string) (Node, error) { 61 | parser := &Parser{ 62 | Lexer: lex.Lex(j), 63 | } 64 | return parser.parse() 65 | } 66 | 67 | func (p *Parser) parse() (node Node, err error) { 68 | defer func() { 69 | if r := recover(); r != nil { 70 | node = nil 71 | err = errors.New(fmt.Sprint(r)) 72 | } 73 | }() 74 | 75 | p.Item = p.Lexer.NextItem() 76 | 77 | switch p.Item.Typ { 78 | case lex.ItemLeftBrace: 79 | return p.parseObject(), nil 80 | case lex.ItemLeftSqrBrace: 81 | return p.parseArray(), nil 82 | case lex.ItemError: 83 | panic(fmt.Sprintf("received error from lexer at pos %v: %v", p.Item.Pos, p.Item.Value)) 84 | default: 85 | panic(fmt.Sprintf("error determining root json type. unexpected item %v", p.Item.Value)) 86 | } 87 | } 88 | 89 | func (p *Parser) parseObject() *ObjectNode { 90 | p.LastItem = p.Item 91 | 92 | object := &ObjectNode{ 93 | NodeType: NodeTypeObject, 94 | Children: make(map[string][]Node, 8), 95 | } 96 | 97 | var currentKey string 98 | for p.Item = p.Lexer.NextItem(); p.Item.Typ != lex.ItemRightBrace; p.Item = p.Lexer.NextItem() { 99 | 100 | switch p.Item.Typ { 101 | case lex.ItemString: 102 | 103 | // A string can indicate that the current lexem is either a key or a value. 104 | // It's a key if the previous lexem is a comma or an opening brace. 105 | // It's a value if the previous lexem is a colon. 106 | if p.LastItem.Typ == lex.ItemComma || p.LastItem.Typ == lex.ItemLeftBrace { 107 | currentKey = p.Item.Value 108 | } else { 109 | object.Children[currentKey] = append(object.Children[currentKey], stringNode) 110 | } 111 | case lex.ItemLeftBrace: 112 | object.Children[currentKey] = append(object.Children[currentKey], p.parseObject()) 113 | case lex.ItemLeftSqrBrace: 114 | object.Children[currentKey] = append(object.Children[currentKey], p.parseArray()) 115 | case lex.ItemBool: 116 | object.Children[currentKey] = append(object.Children[currentKey], boolNode) 117 | case lex.ItemNil: 118 | object.Children[currentKey] = append(object.Children[currentKey], nilNode) 119 | case lex.ItemFloat: 120 | object.Children[currentKey] = append(object.Children[currentKey], floatNode) 121 | case lex.ItemInteger: 122 | object.Children[currentKey] = append(object.Children[currentKey], integerNode) 123 | case lex.ItemColon: 124 | break 125 | case lex.ItemComma: 126 | break 127 | case lex.ItemError: 128 | panic(fmt.Sprintf("received error from lexer. pos: %v, msg: %v", p.Item.Pos, p.Item.Value)) 129 | default: 130 | panic(fmt.Sprintf("error parsing object. unexpected item %v", p.Item.Value)) 131 | } 132 | p.LastItem = p.Item 133 | } 134 | 135 | if p.LastItem.Typ == lex.ItemComma { 136 | panic("error parsing object. a closing curly brace mustn't follow a comma") 137 | } 138 | 139 | return object 140 | } 141 | 142 | func (p *Parser) parseArray() *ArrayNode { 143 | p.LastItem = p.Item 144 | array := &ArrayNode{ 145 | NodeType: NodeTypeArray, 146 | Children: make([]Node, 0, 8), 147 | } 148 | 149 | for p.Item = p.Lexer.NextItem(); p.Item.Typ != lex.ItemRightSqrBrace; p.Item = p.Lexer.NextItem() { 150 | switch p.Item.Typ { 151 | case lex.ItemLeftBrace: 152 | array.Children = append(array.Children, p.parseObject()) 153 | case lex.ItemLeftSqrBrace: 154 | array.Children = append(array.Children, p.parseArray()) 155 | case lex.ItemNil: 156 | array.Children = append(array.Children, nilNode) 157 | case lex.ItemBool: 158 | array.Children = append(array.Children, boolNode) 159 | case lex.ItemString: 160 | array.Children = append(array.Children, stringNode) 161 | case lex.ItemInteger: 162 | array.Children = append(array.Children, integerNode) 163 | case lex.ItemFloat: 164 | array.Children = append(array.Children, floatNode) 165 | case lex.ItemComma: 166 | break 167 | case lex.ItemError: 168 | panic(fmt.Sprintf("received error from lexer. pos: %v, msg: %v", p.Item.Pos, p.Item.Value)) 169 | default: 170 | panic("error parsing array: unexpected item " + p.Item.Value) 171 | } 172 | p.LastItem = p.Item 173 | } 174 | 175 | if p.LastItem.Typ == lex.ItemComma { 176 | panic("error parsing array: a closing square brace mustn't follow a comma") 177 | } 178 | 179 | return array 180 | } 181 | -------------------------------------------------------------------------------- /pkg/parse/parser_test.go: -------------------------------------------------------------------------------- 1 | package parse 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func mkObjectNode(children map[string][]Node) *ObjectNode { 9 | return &ObjectNode{ 10 | Children: children, 11 | NodeType: NodeTypeObject, 12 | } 13 | } 14 | 15 | func mkArrayNode(children []Node) *ArrayNode { 16 | return &ArrayNode{ 17 | Children: children, 18 | NodeType: NodeTypeArray, 19 | } 20 | } 21 | 22 | func mkPrim(typ NodeType) *PrimitiveNode { 23 | return &PrimitiveNode{ 24 | NodeType: typ, 25 | } 26 | } 27 | 28 | func TestParseArrayFromString(t *testing.T) { 29 | type args struct { 30 | name string 31 | json string 32 | } 33 | tests := []struct { 34 | name string 35 | args args 36 | want Node 37 | }{ 38 | { 39 | name: "Empty array", 40 | args: args{ 41 | json: `[]`, 42 | }, 43 | want: mkArrayNode(make([]Node, 0)), 44 | }, 45 | { 46 | name: "Array with strings", 47 | args: args{ 48 | json: `[ "test", "1234", "true" ]`, 49 | }, 50 | want: mkArrayNode( 51 | []Node{ 52 | mkPrim(NodeTypeString), 53 | mkPrim(NodeTypeString), 54 | mkPrim(NodeTypeString), 55 | }, 56 | ), 57 | }, 58 | { 59 | name: "Array with different primitives", 60 | args: args{ 61 | json: `[ "test", 1234, 1.2, true, null ]`, 62 | }, 63 | want: mkArrayNode( 64 | []Node{ 65 | mkPrim(NodeTypeString), 66 | mkPrim(NodeTypeInteger), 67 | mkPrim(NodeTypeFloat), 68 | mkPrim(NodeTypeBool), 69 | mkPrim(NodeTypeNil), 70 | }, 71 | ), 72 | }, 73 | { 74 | name: "Array with objects", 75 | args: args{ 76 | json: `[{ "teststring": "hi" }]`, 77 | }, 78 | want: mkArrayNode( 79 | []Node{ 80 | mkObjectNode( 81 | map[string][]Node{ 82 | "teststring": []Node{mkPrim(NodeTypeString)}, 83 | }, 84 | ), 85 | }, 86 | ), 87 | }, 88 | { 89 | name: "Array with arrays", 90 | args: args{ 91 | json: `[[ "hi", "ho" ]]`, 92 | }, 93 | want: mkArrayNode( 94 | []Node{ 95 | mkArrayNode( 96 | []Node{ 97 | mkPrim(NodeTypeString), 98 | mkPrim(NodeTypeString), 99 | }, 100 | ), 101 | }, 102 | ), 103 | }, 104 | } 105 | for _, tt := range tests { 106 | t.Run(tt.name, func(t *testing.T) { 107 | got, err := ParseFromString(tt.args.json) 108 | if err != nil { 109 | t.Errorf("ParseFromString(): got error %v", err) 110 | } 111 | if !reflect.DeepEqual(got, tt.want) { 112 | t.Errorf("ParseFromString(): \ngot:\n %#v \nwant:\n %#v", got, tt.want) 113 | } 114 | }) 115 | } 116 | } 117 | 118 | func TestParseObjectFromString(t *testing.T) { 119 | type args struct { 120 | name string 121 | json string 122 | } 123 | tests := []struct { 124 | name string 125 | args args 126 | want Node 127 | }{ 128 | { 129 | name: "Empty object", 130 | args: args{ 131 | json: `{}`, 132 | }, 133 | want: mkObjectNode(make(map[string][]Node)), 134 | }, 135 | { 136 | name: "Object with primitives", 137 | args: args{ 138 | json: `{ 139 | "teststring": "hi", 140 | "testbool": true, 141 | "testfloat": 5.4, 142 | "testint": 5, 143 | "testnil": null 144 | }`, 145 | }, 146 | want: mkObjectNode( 147 | map[string][]Node{ 148 | "teststring": []Node{mkPrim(NodeTypeString)}, 149 | "testbool": []Node{mkPrim(NodeTypeBool)}, 150 | "testfloat": []Node{mkPrim(NodeTypeFloat)}, 151 | "testint": []Node{mkPrim(NodeTypeInteger)}, 152 | "testnil": []Node{mkPrim(NodeTypeNil)}, 153 | }, 154 | ), 155 | }, 156 | { 157 | name: "Object with objects", 158 | args: args{ 159 | json: `{ "testobject": { "teststring": "hi" }}`, 160 | }, 161 | want: mkObjectNode( 162 | map[string][]Node{ 163 | "testobject": []Node{ 164 | mkObjectNode( 165 | map[string][]Node{ 166 | "teststring": []Node{mkPrim(NodeTypeString)}, 167 | }, 168 | ), 169 | }, 170 | }, 171 | ), 172 | }, 173 | { 174 | name: "Object with arrays", 175 | args: args{ 176 | json: `{ "testarray": [ "hi", "ho" ]}`, 177 | }, 178 | want: mkObjectNode( 179 | map[string][]Node{ 180 | "testarray": []Node{ 181 | mkArrayNode( 182 | []Node{ 183 | mkPrim(NodeTypeString), 184 | mkPrim(NodeTypeString), 185 | }, 186 | ), 187 | }, 188 | }, 189 | ), 190 | }, 191 | } 192 | for _, tt := range tests { 193 | t.Run(tt.name, func(t *testing.T) { 194 | got, err := ParseFromString(tt.args.json) 195 | if err != nil { 196 | t.Errorf("ParseFromString(): got error %v", err) 197 | } 198 | if !reflect.DeepEqual(got, tt.want) { 199 | t.Errorf("ParseFromString(): \ngot:\n %#v \nwant:\n %#v", got, tt.want) 200 | } 201 | }) 202 | } 203 | } 204 | 205 | func TestParseInvalidJSON(t *testing.T) { 206 | tests := []struct { 207 | name string 208 | json string 209 | }{ 210 | { 211 | name: "array with comma before closing square brace", 212 | json: "[ true, ]", 213 | }, 214 | { 215 | name: "object with comma before closing curly brace", 216 | json: `{ "test": "hi", }`, 217 | }, 218 | } 219 | 220 | for _, test := range tests { 221 | if _, err := ParseFromString(test.json); err == nil { 222 | t.Errorf("TestParseInvalidJSON(): expected error, but received none. input: %v", test.json) 223 | } 224 | } 225 | } 226 | --------------------------------------------------------------------------------