001package org.json;
002
003/*
004Copyright (c) 2002 JSON.org
005
006Permission is hereby granted, free of charge, to any person obtaining a copy
007of this software and associated documentation files (the "Software"), to deal
008in the Software without restriction, including without limitation the rights
009to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
010copies of the Software, and to permit persons to whom the Software is
011furnished to do so, subject to the following conditions:
012
013The above copyright notice and this permission notice shall be included in all
014copies or substantial portions of the Software.
015
016The Software shall be used for Good, not Evil.
017
018THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
019IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
020FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
021AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
022LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
023OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
024SOFTWARE.
025*/
026
027/**
028 * This provides static methods to convert comma delimited text into a
029 * JSONArray, and to convert a JSONArray into comma delimited text. Comma
030 * delimited text is a very popular format for data interchange. It is
031 * understood by most database, spreadsheet, and organizer programs.
032 * <p>
033 * Each row of text represents a row in a table or a data record. Each row
034 * ends with a NEWLINE character. Each row contains one or more values.
035 * Values are separated by commas. A value can contain any character except
036 * for comma, unless is is wrapped in single quotes or double quotes.
037 * <p>
038 * The first row usually contains the names of the columns.
039 * <p>
040 * A comma delimited list can be converted into a JSONArray of JSONObjects.
041 * The names for the elements in the JSONObjects can be taken from the names
042 * in the first row.
043 * @author JSON.org
044 * @version 2015-12-09
045 */
046public class CDL {
047
048    /**
049     * Get the next value. The value can be wrapped in quotes. The value can
050     * be empty.
051     * @param x A JSONTokener of the source text.
052     * @return The value string, or null if empty.
053     * @throws JSONException if the quoted string is badly formed.
054     */
055    private static String getValue(JSONTokener x) throws JSONException {
056        char c;
057        char q;
058        StringBuffer sb;
059        do {
060            c = x.next();
061        } while (c == ' ' || c == '\t');
062        switch (c) {
063        case 0:
064            return null;
065        case '"':
066        case '\'':
067            q = c;
068            sb = new StringBuffer();
069            for (;;) {
070                c = x.next();
071                if (c == q) {
072                    break;
073                }
074                if (c == 0 || c == '\n' || c == '\r') {
075                    throw x.syntaxError("Missing close quote '" + q + "'.");
076                }
077                sb.append(c);
078            }
079            return sb.toString();
080        case ',':
081            x.back();
082            return "";
083        default:
084            x.back();
085            return x.nextTo(',');
086        }
087    }
088
089    /**
090     * Produce a JSONArray of strings from a row of comma delimited values.
091     * @param x A JSONTokener of the source text.
092     * @return A JSONArray of strings.
093     * @throws JSONException
094     */
095    public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
096        JSONArray ja = new JSONArray();
097        for (;;) {
098            String value = getValue(x);
099            char c = x.next();
100            if (value == null ||
101                    (ja.length() == 0 && value.length() == 0 && c != ',')) {
102                return null;
103            }
104            ja.put(value);
105            for (;;) {
106                if (c == ',') {
107                    break;
108                }
109                if (c != ' ') {
110                    if (c == '\n' || c == '\r' || c == 0) {
111                        return ja;
112                    }
113                    throw x.syntaxError("Bad character '" + c + "' (" +
114                            (int)c + ").");
115                }
116                c = x.next();
117            }
118        }
119    }
120
121    /**
122     * Produce a JSONObject from a row of comma delimited text, using a
123     * parallel JSONArray of strings to provides the names of the elements.
124     * @param names A JSONArray of names. This is commonly obtained from the
125     *  first row of a comma delimited text file using the rowToJSONArray
126     *  method.
127     * @param x A JSONTokener of the source text.
128     * @return A JSONObject combining the names and values.
129     * @throws JSONException
130     */
131    public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x)
132            throws JSONException {
133        JSONArray ja = rowToJSONArray(x);
134        return ja != null ? ja.toJSONObject(names) :  null;
135    }
136
137    /**
138     * Produce a comma delimited text row from a JSONArray. Values containing
139     * the comma character will be quoted. Troublesome characters may be
140     * removed.
141     * @param ja A JSONArray of strings.
142     * @return A string ending in NEWLINE.
143     */
144    public static String rowToString(JSONArray ja) {
145        StringBuilder sb = new StringBuilder();
146        for (int i = 0; i < ja.length(); i += 1) {
147            if (i > 0) {
148                sb.append(',');
149            }
150            Object object = ja.opt(i);
151            if (object != null) {
152                String string = object.toString();
153                if (string.length() > 0 && (string.indexOf(',') >= 0 ||
154                        string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
155                        string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
156                    sb.append('"');
157                    int length = string.length();
158                    for (int j = 0; j < length; j += 1) {
159                        char c = string.charAt(j);
160                        if (c >= ' ' && c != '"') {
161                            sb.append(c);
162                        }
163                    }
164                    sb.append('"');
165                } else {
166                    sb.append(string);
167                }
168            }
169        }
170        sb.append('\n');
171        return sb.toString();
172    }
173
174    /**
175     * Produce a JSONArray of JSONObjects from a comma delimited text string,
176     * using the first row as a source of names.
177     * @param string The comma delimited text.
178     * @return A JSONArray of JSONObjects.
179     * @throws JSONException
180     */
181    public static JSONArray toJSONArray(String string) throws JSONException {
182        return toJSONArray(new JSONTokener(string));
183    }
184
185    /**
186     * Produce a JSONArray of JSONObjects from a comma delimited text string,
187     * using the first row as a source of names.
188     * @param x The JSONTokener containing the comma delimited text.
189     * @return A JSONArray of JSONObjects.
190     * @throws JSONException
191     */
192    public static JSONArray toJSONArray(JSONTokener x) throws JSONException {
193        return toJSONArray(rowToJSONArray(x), x);
194    }
195
196    /**
197     * Produce a JSONArray of JSONObjects from a comma delimited text string
198     * using a supplied JSONArray as the source of element names.
199     * @param names A JSONArray of strings.
200     * @param string The comma delimited text.
201     * @return A JSONArray of JSONObjects.
202     * @throws JSONException
203     */
204    public static JSONArray toJSONArray(JSONArray names, String string)
205            throws JSONException {
206        return toJSONArray(names, new JSONTokener(string));
207    }
208
209    /**
210     * Produce a JSONArray of JSONObjects from a comma delimited text string
211     * using a supplied JSONArray as the source of element names.
212     * @param names A JSONArray of strings.
213     * @param x A JSONTokener of the source text.
214     * @return A JSONArray of JSONObjects.
215     * @throws JSONException
216     */
217    public static JSONArray toJSONArray(JSONArray names, JSONTokener x)
218            throws JSONException {
219        if (names == null || names.length() == 0) {
220            return null;
221        }
222        JSONArray ja = new JSONArray();
223        for (;;) {
224            JSONObject jo = rowToJSONObject(names, x);
225            if (jo == null) {
226                break;
227            }
228            ja.put(jo);
229        }
230        if (ja.length() == 0) {
231            return null;
232        }
233        return ja;
234    }
235
236
237    /**
238     * Produce a comma delimited text from a JSONArray of JSONObjects. The
239     * first row will be a list of names obtained by inspecting the first
240     * JSONObject.
241     * @param ja A JSONArray of JSONObjects.
242     * @return A comma delimited text.
243     * @throws JSONException
244     */
245    public static String toString(JSONArray ja) throws JSONException {
246        JSONObject jo = ja.optJSONObject(0);
247        if (jo != null) {
248            JSONArray names = jo.names();
249            if (names != null) {
250                return rowToString(names) + toString(names, ja);
251            }
252        }
253        return null;
254    }
255
256    /**
257     * Produce a comma delimited text from a JSONArray of JSONObjects using
258     * a provided list of names. The list of names is not included in the
259     * output.
260     * @param names A JSONArray of strings.
261     * @param ja A JSONArray of JSONObjects.
262     * @return A comma delimited text.
263     * @throws JSONException
264     */
265    public static String toString(JSONArray names, JSONArray ja)
266            throws JSONException {
267        if (names == null || names.length() == 0) {
268            return null;
269        }
270        StringBuffer sb = new StringBuffer();
271        for (int i = 0; i < ja.length(); i += 1) {
272            JSONObject jo = ja.optJSONObject(i);
273            if (jo != null) {
274                sb.append(rowToString(jo.toJSONArray(names)));
275            }
276        }
277        return sb.toString();
278    }
279}