JsonReader implements DataReader<JsonReadOptions> { @Override public Table read(JsonReadOptions options) throws IOException { JsonNode jsonObj = mapper.readTree(options.source().createReader(null)); if (options.path() != null) { jsonObj = jsonObj.at(options.path()); } if (!jsonObj.isArray()) { throw new IllegalStateException( "Only reading a JSON array is currently supported. The array must hold an array or object for each row."); } if (jsonObj.size() == 0) { return Table.create(options.tableName()); } JsonNode firstNode = jsonObj.get(0); if (firstNode.isArray()) { return convertArrayOfArrays(jsonObj, options); } return convertArrayOfObjects(jsonObj, options); }  static void register(ReaderRegistry registry); @Override Table read(JsonReadOptions options); @Override Table read(Source source);  }
@Test public void arrayOfArraysWithHeader() { String json = "[[\"Date\",\"Value\"],[1453438800000,-2.1448117025014],[1454043600000,-2.9763153817574],[1454648400000,-2.9545283436391]]"; Table table = Table.read().string(json, "json"); assertEquals(2, table.columnCount()); assertEquals(3, table.rowCount()); assertEquals("Date", table.column(0).name()); assertEquals("Value", table.column(1).name()); assertEquals(ColumnType.LONG, table.columnTypes()[0]); assertEquals(1453438800000L, table.column("Date").get(0)); }
@Test public void arrayOfArraysNoHeader() { String json = "[[1453438800000,-2.1448117025014],[1454043600000,-2.9763153817574],[1454648400000,-2.9545283436391]]"; Table table = Table.read().string(json, "json"); assertEquals(2, table.columnCount()); assertEquals(3, table.rowCount()); assertEquals(ColumnType.LONG, table.columnTypes()[0]); }
@Test public void arrayOfNestedObjects() { String json = "[{\"a\":1453438800000,\"b\":{\"c\":-2.1448117025014}},{\"a\":1454043600000,\"b\":{\"c\":-2.9763153817574}},{\"a\":1454648400000,\"b\":{\"c\":-2.9545283436391}}]"; Table table = Table.read().string(json, "json"); assertEquals(2, table.columnCount()); assertEquals(3, table.rowCount()); assertEquals("a", table.column(0).name()); assertEquals("b.c", table.column(1).name()); assertEquals(ColumnType.LONG, table.columnTypes()[0]); }
@Test public void arrayOfRowsWithIncompleteIndexes() { String json = "[" + "{\"A\" : \"123\", \"B\" : \"456\"}," + "{\"B\" : \"789\", \"C\" : \"123\"}" + "]"; Table expected = Table.create( IntColumn.create("A", new int[] {123, Integer.MIN_VALUE}), IntColumn.create("B", new int[] {456, 789}), IntColumn.create("C", new int[] {Integer.MIN_VALUE, 123})); Table actual = Table.read().string(json, "json"); assertEquals(ColumnType.INTEGER, actual.columnTypes()[0]); assertEquals(expected.column("A").asList(), actual.column("A").asList()); assertEquals(expected.column("B").asList(), actual.column("B").asList()); assertEquals(expected.column("C").asList(), actual.column("C").asList()); }