├── .gitignore ├── LICENSE ├── OWNERS ├── README.md ├── jsonpps ├── pom.xml └── src ├── main └── java │ └── com │ └── bazaarvoice │ └── jsonpps │ └── PrettyPrintJson.java └── test └── java └── com └── bazaarvoice └── jsonpps └── PrettyPrintJsonTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # IntelliJ Files 2 | .idea/ 3 | *.ipr 4 | *.iws 5 | *.iml 6 | 7 | # Eclipse Files 8 | .classpath 9 | .project 10 | 11 | # Build outputs 12 | target/ 13 | reports/ 14 | 15 | # OS hidden files 16 | .DS_Store 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /OWNERS: -------------------------------------------------------------------------------- 1 | robby.morgan@bazaarvoice.com 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | jsonpps 2 | ====================================== 3 | 4 | A streaming JSON pretty printer that can format multi-GB input files. This repo is being archived and made read-only on August 30th, 2021 because it is dormant. 5 | 6 | Pretty prints a whitespace-separated sequence of JSON values. Example: 7 | ``` 8 | $ echo 'false 0 "string" [1,2,3] {"a":4} null' | jsonpps 9 | false 10 | 0 11 | "string" 12 | [ 1, 2, 3 ] 13 | { 14 | "a" : 4 15 | } 16 | null 17 | ``` 18 | 19 | Why yet another JSON pretty printer? 20 | 21 | * Processes very large JSON files in a memory-efficient way. Does not read entire files into memory at once. 22 | 23 | * Preserves the order of key/value pairs in JSON objects unlike, for example, `python -mjson.tool`. 24 | 25 | * Accepts input that already has some formatting such as newline characters. 26 | 27 | * Unless `--strict` is specified, accepts certain JavaScript syntax such as comments, unquoted keys, single quoted strings. Example: 28 | 29 | ``` 30 | $ echo "{key: 'value' /*inline comment*/} // line comment" | jsonpps 31 | { 32 | "key" : "value" 33 | } 34 | ``` 35 | 36 | Uses the [Jackson streaming JSON parser] (http://wiki.fasterxml.com/JacksonHome). 37 | 38 | Usage 39 | ----- 40 | 41 | ``` 42 | $ jsonpps -h 43 | usage: 44 | jsonpps - pretty print stdin 45 | jsonpps - - pretty print stdin 46 | jsonpps ... - pretty print file(s) 47 | 48 | options: 49 | -o - output file 50 | --strict - reject non-conforming json 51 | ``` 52 | 53 | Installation 54 | ------------ 55 | 56 | Requires Java and Maven. 57 | 58 | ``` 59 | # Download and build streaming jsonpps 60 | git clone git@github.com:bazaarvoice/jsonpps.git 61 | cd jsonpps 62 | mvn clean package 63 | 64 | # Install 65 | sudo ln -s $(pwd)/jsonpps /usr/local/bin/ 66 | ``` 67 | 68 | Or, if you have [Homebrew on OS/X] (http://brew.sh/): 69 | 70 | ``` 71 | brew install https://raw.github.com/shawnsmith/homebrew/master/Library/Formula/jsonpps.rb 72 | ``` 73 | -------------------------------------------------------------------------------- /jsonpps: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -o errexit 3 | set -o nounset 4 | 5 | # Figure out where this script lives (follow symbolic links). Emulate GNU readlink -f. 6 | function readlink_for_osx() { 7 | FILENAME="$1" 8 | while true; do 9 | cd "$( dirname "$FILENAME" )" 10 | FILENAME="$( basename "$FILENAME" )" 11 | [ -L "$FILENAME" ] || break 12 | FILENAME="$( readlink "$FILENAME" )" 13 | done 14 | echo "$(pwd -P)/$FILENAME" 15 | } 16 | JSONPPS_DIR="$( dirname "$( readlink_for_osx "${BASH_SOURCE:-$0}" )" )" 17 | JSONPPS_JAR="$( echo "${JSONPPS_DIR}"/target/jsonpps-*.jar )" 18 | 19 | java -Xms64m -Xmx64m -jar "${JSONPPS_JAR}" "$@" 20 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 4.0.0 5 | 6 | 7 | com.bazaarvoice.commons 8 | bv-opensource-super-pom 9 | 1.2 10 | 11 | 12 | 13 | com.bazaarvoice.jsonpps 14 | jsonpps 15 | 1.2-SNAPSHOT 16 | jar 17 | 18 | 19 | https://github.com/bazaarvoice/jsonpps 20 | scm:git:git@github.com:bazaarvoice/jsonpps.git 21 | scm:git:git@github.com:bazaarvoice/jsonpps.git 22 | 23 | 24 | JSON Streaming Pretty Printer 25 | http://github.com/bazaarvoice/jsonpps 26 | 27 | 28 | Apache License 2.0 29 | http://www.apache.org/licenses/LICENSE-2.0 30 | repo 31 | 32 | 33 | 34 | 35 | 2.4.2 36 | 37 | 38 | 39 | 40 | 41 | com.fasterxml.jackson.core 42 | jackson-core 43 | ${jackson.version} 44 | 45 | 46 | com.fasterxml.jackson.core 47 | jackson-databind 48 | ${jackson.version} 49 | 50 | 51 | net.sourceforge.argparse4j 52 | argparse4j 53 | 0.4.4 54 | 55 | 56 | 57 | 58 | junit 59 | junit 60 | 4.11 61 | test 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | maven-compiler-plugin 71 | 72 | -Xlint:all 73 | true 74 | true 75 | 76 | 77 | 78 | 79 | 80 | 81 | org.apache.rat 82 | apache-rat-plugin 83 | 0.9 84 | 85 | 86 | **/*.java 87 | 88 | 89 | 90 | 91 | rat-check 92 | test 93 | 94 | check 95 | 96 | 97 | 98 | 99 | 100 | org.apache.maven.plugins 101 | maven-shade-plugin 102 | 1.6 103 | 104 | false 105 | 106 | 107 | *:* 108 | 109 | META-INF/*.SF 110 | META-INF/*.DSA 111 | META-INF/*.RSA 112 | 113 | 114 | 115 | 116 | 117 | 118 | package 119 | 120 | shade 121 | 122 | 123 | 124 | 125 | 126 | com.bazaarvoice.jsonpps.PrettyPrintJson 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | -------------------------------------------------------------------------------- /src/main/java/com/bazaarvoice/jsonpps/PrettyPrintJson.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Bazaarvoice, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.bazaarvoice.jsonpps; 17 | 18 | import com.fasterxml.jackson.core.JsonEncoding; 19 | import com.fasterxml.jackson.core.JsonFactory; 20 | import com.fasterxml.jackson.core.JsonGenerator; 21 | import com.fasterxml.jackson.core.JsonParser; 22 | import com.fasterxml.jackson.core.JsonToken; 23 | import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; 24 | import com.fasterxml.jackson.databind.ObjectMapper; 25 | import com.fasterxml.jackson.databind.SerializationFeature; 26 | import net.sourceforge.argparse4j.ArgumentParsers; 27 | import net.sourceforge.argparse4j.impl.Arguments; 28 | import net.sourceforge.argparse4j.inf.ArgumentParser; 29 | import net.sourceforge.argparse4j.inf.ArgumentParserException; 30 | import net.sourceforge.argparse4j.inf.Namespace; 31 | 32 | import java.io.File; 33 | import java.io.IOException; 34 | import java.io.InputStream; 35 | import java.io.OutputStream; 36 | import java.util.Collection; 37 | import java.util.Collections; 38 | import java.util.List; 39 | import java.util.Map; 40 | import java.util.UUID; 41 | 42 | import static com.fasterxml.jackson.core.JsonTokenId.ID_FIELD_NAME; 43 | import static com.fasterxml.jackson.core.JsonTokenId.ID_START_ARRAY; 44 | import static com.fasterxml.jackson.core.JsonTokenId.ID_START_OBJECT; 45 | 46 | public class PrettyPrintJson { 47 | private static final File STDINOUT = new File("-"); 48 | 49 | private int flatten; 50 | private boolean sortKeys; 51 | private boolean strict; 52 | private boolean wrap; 53 | private InputStream stdin = System.in; 54 | private OutputStream stdout = System.out; 55 | 56 | public static void main(String[] args) throws Exception { 57 | try { 58 | ArgumentParser parser = ArgumentParsers.newArgumentParser("jsonpps") 59 | .description("A streaming JSON pretty printer that can format multi-GB input files.") 60 | .defaultHelp(true); 61 | parser.addArgument("-o", "--out") 62 | .type(Arguments.fileType()) 63 | .setDefault(STDINOUT) 64 | .help("output file"); 65 | parser.addArgument("--flatten") 66 | .metavar("N") 67 | .type(Integer.class) 68 | .setDefault(0) 69 | .help("flatten the top-N levels of object/array structure"); 70 | parser.addArgument("-i", "--in-place") 71 | .action(Arguments.storeTrue()) 72 | .help("modify the original file(s)"); 73 | parser.addArgument("-S", "--sort-keys") 74 | .action(Arguments.storeTrue()) 75 | .help("emit objects with keys in sorted order. this increases memory requirements since objects must be buffered in memory."); 76 | parser.addArgument("--strict") 77 | .action(Arguments.storeTrue()) 78 | .help("reject non-conforming json"); 79 | parser.addArgument("--wrap") 80 | .action(Arguments.storeTrue()) 81 | .help("wrap all output in a json array"); 82 | parser.addArgument("--unwrap") 83 | .action(Arguments.storeTrue()) 84 | .help("flatten the top level of object/array structure"); 85 | parser.addArgument("in") 86 | .nargs("*") 87 | .type(Arguments.fileType().acceptSystemIn().verifyExists().verifyIsFile().verifyCanRead()) 88 | .setDefault(new File[]{STDINOUT}) 89 | .help("input file(s)"); 90 | Namespace ns; 91 | try { 92 | ns = parser.parseArgs(args); 93 | } catch (ArgumentParserException e) { 94 | parser.handleError(e); 95 | System.exit(2); 96 | return; 97 | } 98 | 99 | PrettyPrintJson jsonpp = new PrettyPrintJson(); 100 | File outputFile = ns.get("out"); 101 | List inputFiles = ns.getList("in"); 102 | boolean inPlace = ns.getBoolean("in_place"); 103 | jsonpp.setFlatten(ns.getInt("flatten")); 104 | jsonpp.setSortKeys(ns.getBoolean("sort_keys")); 105 | jsonpp.setStrict(ns.getBoolean("strict")); 106 | jsonpp.setWrap(ns.getBoolean("wrap")); 107 | if (ns.getBoolean("unwrap")) { 108 | jsonpp.setFlatten(1); 109 | } 110 | 111 | if (!inPlace) { 112 | // Pretty print all input files to a single output 113 | jsonpp.prettyPrint(inputFiles, outputFile); 114 | 115 | } else { 116 | // Pretty print all input files back to themselves. 117 | if (outputFile != STDINOUT) { // use "!=" not "!.equals()" since default is ok but "-o -" is not. 118 | System.err.println("error: -o and --in-place are mutually exclusive"); 119 | System.exit(2); 120 | } 121 | if (inputFiles.isEmpty()) { 122 | System.err.println("error: --in-place requires at least one input file"); 123 | System.exit(2); 124 | } 125 | if (inputFiles.contains(STDINOUT)) { 126 | System.err.println("error: --in-place cannot operate on stdin"); 127 | System.exit(2); 128 | } 129 | for (File inputFile : inputFiles) { 130 | jsonpp.prettyPrint(inputFile, inputFile); 131 | } 132 | } 133 | 134 | } catch (Throwable t) { 135 | t.printStackTrace(); 136 | System.err.println(t.toString()); 137 | System.exit(1); 138 | } 139 | } 140 | 141 | public void setFlatten(int flatten) { 142 | this.flatten = flatten; 143 | } 144 | 145 | public void setSortKeys(boolean sortKeys) { 146 | this.sortKeys = sortKeys; 147 | } 148 | 149 | public void setStrict(boolean strict) { 150 | this.strict = strict; 151 | } 152 | 153 | public void setWrap(boolean wrap) { 154 | this.wrap = wrap; 155 | } 156 | 157 | public void setStdin(InputStream stdin) { 158 | this.stdin = stdin; 159 | } 160 | 161 | public void setStdout(OutputStream stdout) { 162 | this.stdout = stdout; 163 | } 164 | 165 | public void prettyPrint(File inputFile, File outputFile) throws IOException { 166 | prettyPrint(Collections.singletonList(inputFile), outputFile); 167 | } 168 | 169 | public void prettyPrint(List inputFiles, File outputFile) throws IOException { 170 | JsonFactory factory = new JsonFactory(); 171 | factory.disable(JsonFactory.Feature.INTERN_FIELD_NAMES); 172 | if (!strict) { 173 | factory.enable(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER); 174 | factory.enable(JsonParser.Feature.ALLOW_COMMENTS); 175 | factory.enable(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS); 176 | factory.enable(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS); 177 | factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES); 178 | factory.enable(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS); 179 | factory.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES); 180 | } 181 | 182 | ObjectMapper mapper = null; 183 | if (sortKeys) { 184 | mapper = new ObjectMapper(factory); 185 | mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); 186 | mapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); 187 | } 188 | 189 | // Open the output stream and create the Json emitter. 190 | JsonGenerator generator; 191 | File tempOutputFile = null; 192 | if (STDINOUT.equals(outputFile)) { 193 | generator = factory.createGenerator(stdout, JsonEncoding.UTF8); 194 | } else if (!caseInsensitiveContains(inputFiles, outputFile)) { 195 | generator = factory.createGenerator(outputFile, JsonEncoding.UTF8); 196 | } else { 197 | // Writing to an input file.. use a temp file to stage the output until we're done. 198 | tempOutputFile = getTemporaryFileFor(outputFile); 199 | generator = factory.createGenerator(tempOutputFile, JsonEncoding.UTF8); 200 | } 201 | try { 202 | // Separate top-level objects by a newline in the output. 203 | String newline = System.getProperty("line.separator"); 204 | generator.setPrettyPrinter(new DefaultPrettyPrinter(newline)); 205 | 206 | if (wrap) { 207 | generator.writeStartArray(); 208 | } 209 | 210 | for (File inputFile : inputFiles) { 211 | JsonParser parser; 212 | if (STDINOUT.equals(inputFile)) { 213 | parser = factory.createParser(stdin); 214 | } else { 215 | parser = factory.createParser(inputFile); 216 | } 217 | try { 218 | while (parser.nextToken() != null) { 219 | copyCurrentStructure(parser, mapper, 0, generator); 220 | } 221 | } finally { 222 | parser.close(); 223 | } 224 | } 225 | 226 | if (wrap) { 227 | generator.writeEndArray(); 228 | } 229 | 230 | generator.writeRaw(newline); 231 | } finally { 232 | generator.close(); 233 | } 234 | if (tempOutputFile != null && !tempOutputFile.renameTo(outputFile)) { 235 | System.err.println("error: unable to rename temporary file to output: " + outputFile); 236 | System.exit(1); 237 | } 238 | } 239 | 240 | private void copyCurrentStructure(JsonParser parser, ObjectMapper mapper, int depth, JsonGenerator generator) throws IOException { 241 | // Avoid using the mapper to parse the entire input until we absolutely must. This allows pretty 242 | // printing huge top-level arrays (that wouldn't fit in memory) containing smaller objects (that 243 | // individually do fit in memory) where the objects are printed with sorted keys. 244 | JsonToken t = parser.getCurrentToken(); 245 | if (t == null) { 246 | generator.copyCurrentStructure(parser); // Will report the error of a null token. 247 | return; 248 | } 249 | int id = t.id(); 250 | if (id == ID_FIELD_NAME) { 251 | if (depth > flatten) { 252 | generator.writeFieldName(parser.getCurrentName()); 253 | } 254 | t = parser.nextToken(); 255 | id = t.id(); 256 | } 257 | switch (id) { 258 | case ID_START_OBJECT: 259 | if (sortKeys && depth >= flatten) { 260 | // Load the entire object in memory so we can sort its keys and serialize it back out. 261 | mapper.writeValue(generator, parser.readValueAs(Map.class)); 262 | } else { 263 | // Don't load the whole object into memory. Copy it in a memory-efficient streaming fashion. 264 | if (depth >= flatten) { 265 | generator.writeStartObject(); 266 | } 267 | while (parser.nextToken() != JsonToken.END_OBJECT) { 268 | copyCurrentStructure(parser, mapper, depth + 1, generator); 269 | } 270 | if (depth >= flatten) { 271 | generator.writeEndObject(); 272 | } 273 | } 274 | break; 275 | case ID_START_ARRAY: 276 | // Don't load the whole array into memory. Copy it in a memory-efficient streaming fashion. 277 | if (depth >= flatten) { 278 | generator.writeStartArray(); 279 | } 280 | while (parser.nextToken() != JsonToken.END_ARRAY) { 281 | copyCurrentStructure(parser, mapper, depth + 1, generator); 282 | } 283 | if (depth >= flatten) { 284 | generator.writeEndArray(); 285 | } 286 | break; 287 | default: 288 | generator.copyCurrentEvent(parser); 289 | break; 290 | } 291 | } 292 | 293 | private boolean caseInsensitiveContains(Collection srcs, File dest) throws IOException { 294 | for (File src : srcs) { 295 | if (!STDINOUT.equals(src) && src.getCanonicalPath().equalsIgnoreCase(dest.getCanonicalPath())) { 296 | return true; 297 | } 298 | } 299 | return false; 300 | } 301 | 302 | private File getTemporaryFileFor(File file) { 303 | // The temporary file must exist in the same directory as the destination file so we can 304 | // reliably rename it at the end w/o copying across volumes. Use a secure random UUID to 305 | // name the file since there is mathematically no realistic chance of collisions. 306 | String randomSuffix = UUID.randomUUID().toString().replace("-", ""); 307 | File tempFile = new File(file.getParentFile(), "_" + file.getName() + "." + randomSuffix); 308 | tempFile.deleteOnExit(); 309 | return tempFile; 310 | } 311 | } 312 | -------------------------------------------------------------------------------- /src/test/java/com/bazaarvoice/jsonpps/PrettyPrintJsonTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Bazaarvoice, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.bazaarvoice.jsonpps; 17 | 18 | import org.junit.Test; 19 | 20 | import java.io.ByteArrayInputStream; 21 | import java.io.ByteArrayOutputStream; 22 | import java.io.File; 23 | import java.io.InputStream; 24 | import java.math.BigInteger; 25 | 26 | import static org.junit.Assert.assertEquals; 27 | 28 | public class PrettyPrintJsonTest { 29 | 30 | @Test 31 | public void testMultiple() throws Exception { 32 | doTest("1 2 3", "1\n2\n3\n"); 33 | } 34 | 35 | @Test 36 | public void testNull() throws Exception { 37 | doTest("null", "null\n"); 38 | } 39 | 40 | @Test 41 | public void testBoolean() throws Exception { 42 | doTest("true", "true\n"); 43 | doTest("false", "false\n"); 44 | } 45 | 46 | @Test 47 | public void testInteger() throws Exception { 48 | doTest("1", "1\n"); 49 | doTest("01", "1\n"); 50 | doTest(Long.toString(Long.MIN_VALUE), Long.MIN_VALUE + "\n"); 51 | doTest(BigInteger.TEN.pow(123).toString(), BigInteger.TEN.pow(123) + "\n"); 52 | } 53 | 54 | @Test 55 | public void testDouble() throws Exception { 56 | doTest("1.23456789", "1.23456789\n"); 57 | } 58 | 59 | @Test 60 | public void testString() throws Exception { 61 | doTest("\"hello\tw\u00f3rld\n\"", "\"hello\\tw\u00f3rld\\n\"\n"); 62 | } 63 | 64 | @Test 65 | public void testArray() throws Exception { 66 | doTest("[1,2,\"three\"]", "[ 1, 2, \"three\" ]\n"); 67 | doTest("[{\"b\":2,\"a\":1,\"C\":3},true]", "[ {\n \"b\" : 2,\n \"a\" : 1,\n \"C\" : 3\n}, true ]\n"); 68 | } 69 | 70 | @Test 71 | public void testObject() throws Exception { 72 | doTest("{\"key1\":\"value1\",\"key2\":2}", "{\n \"key1\" : \"value1\",\n \"key2\" : 2\n}\n"); 73 | doTest("{\"b\":2,\"a\":1,\"C\":3}", "{\n \"b\" : 2,\n \"a\" : 1,\n \"C\" : 3\n}\n"); 74 | } 75 | 76 | @Test 77 | public void testNewlinesInInput() throws Exception { 78 | doTest("[\n1,\n2\n,\"three\"\n]", "[ 1, 2, \"three\" ]\n"); 79 | } 80 | 81 | @Test 82 | public void testSingleQuotes() throws Exception { 83 | doTest("'string' {'key1':'value1'}", "\"string\"\n{\n \"key1\" : \"value1\"\n}\n"); 84 | } 85 | 86 | @Test 87 | public void testMissingQuotes() throws Exception { 88 | doTest("{key1:'value1'}", "{\n \"key1\" : \"value1\"\n}\n"); 89 | } 90 | 91 | @Test 92 | public void testSortKeys() throws Exception { 93 | PrettyPrintJson jsonpps = new PrettyPrintJson(); 94 | jsonpps.setSortKeys(true); 95 | doTest("[3,2,1]", "[ 3, 2, 1 ]\n"); 96 | doTest(jsonpps, "{\"b\":2,\"a\":1,\"C\":3}", "{\n \"C\" : 3,\n \"a\" : 1,\n \"b\" : 2\n}\n"); 97 | doTest(jsonpps, "[{\"b\":2,\"a\":1,\"C\":3},true]", "[ {\n \"C\" : 3,\n \"a\" : 1,\n \"b\" : 2\n}, true ]\n"); 98 | } 99 | 100 | @Test 101 | public void testFlattenArray() throws Exception { 102 | PrettyPrintJson jsonpps = new PrettyPrintJson(); 103 | jsonpps.setFlatten(2); 104 | 105 | doTest(jsonpps, "[3,2,[1],[[0]]]", "3\n2\n1\n[ 0 ]\n"); 106 | } 107 | 108 | @Test 109 | public void testFlattenObject() throws Exception { 110 | PrettyPrintJson jsonpps = new PrettyPrintJson(); 111 | 112 | jsonpps.setFlatten(1); 113 | doTest(jsonpps, "{a:1}", "1\n"); 114 | doTest(jsonpps, "{a:1,b:{c:2}}", "1\n{\n \"c\" : 2\n}\n"); 115 | 116 | jsonpps.setFlatten(2); 117 | jsonpps.setSortKeys(true); // Sorting should only occur at nesting depths that aren't flattened. 118 | doTest(jsonpps, "{a:{b:{c:{d:1,E:2}}},F:2,g:[3,4]}", "{\n \"c\" : {\n \"E\" : 2,\n \"d\" : 1\n }\n}\n2\n3\n4\n"); 119 | } 120 | 121 | @Test 122 | public void testWrap() throws Exception { 123 | PrettyPrintJson jsonpps = new PrettyPrintJson(); 124 | jsonpps.setWrap(true); 125 | 126 | doTest(jsonpps, "1 2 3 [4]", "[ 1, 2, 3, [ 4 ] ]\n"); 127 | } 128 | 129 | private void doTest(String input, String output) throws Exception { 130 | doTest(new PrettyPrintJson(), input, output); 131 | } 132 | 133 | private void doTest(PrettyPrintJson jsonpps, String input, String output) throws Exception { 134 | output = output.replaceAll("\n", System.getProperty("line.separator")); 135 | InputStream stdin = new ByteArrayInputStream(input.getBytes("UTF-8")); 136 | ByteArrayOutputStream stdout = new ByteArrayOutputStream(); 137 | 138 | jsonpps.setStdin(stdin); 139 | jsonpps.setStdout(stdout); 140 | jsonpps.prettyPrint(new File("-"), new File("-")); 141 | 142 | assertEquals(output, stdout.toString("UTF-8")); 143 | } 144 | } 145 | --------------------------------------------------------------------------------