From a9f8a2d24ce24ee8a4163577245d775b8013b0f9 Mon Sep 17 00:00:00 2001 From: Dhivya Kanakabala Date: Wed, 27 Nov 2019 17:38:27 +0530 Subject: [PATCH] enhancement_SFrame.read_json_should_accept_a_JSON_string_in_addition_to_files_2564 --- .../turicreate/data_structures/sframe.py | 19 ++++++++++++------- src/python/turicreate/test/test_sframe.py | 7 +++++++ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/python/turicreate/data_structures/sframe.py b/src/python/turicreate/data_structures/sframe.py index cb5db0c05f..b8206b07a0 100644 --- a/src/python/turicreate/data_structures/sframe.py +++ b/src/python/turicreate/data_structures/sframe.py @@ -1603,13 +1603,18 @@ def read_json(cls, [3 rows x 1 columns] """ if orient == "records": - g = SArray.read_json(url) - if len(g) == 0: - return SFrame() - if g.dtype != dict: - raise RuntimeError("Invalid input JSON format. Expected list of dictionaries") - g = SFrame({'X1':g}) - return g.unpack('X1','') + if type(url)==str and url[0] !='{' : + g = SArray.read_json(url) + if len(g) == 0: + return SFrame() + if g.dtype != dict: + raise RuntimeError("Invalid input JSON format. Expected list of dictionaries") + g = SFrame({'X1':g}) + return g.unpack('X1','') + elif type(url)==str and url[0] =='{' : + url=pandas.read_json(url) + url=SFrame(url) + return url elif orient == "lines": g = cls.read_csv(url, header=False,na_values=['null'],true_values=['true'],false_values=['false'], _only_raw_string_substitutions=True) diff --git a/src/python/turicreate/test/test_sframe.py b/src/python/turicreate/test/test_sframe.py index 91a0c8cfcd..a7e27bfa21 100644 --- a/src/python/turicreate/test/test_sframe.py +++ b/src/python/turicreate/test/test_sframe.py @@ -201,6 +201,13 @@ def test_auto_parse_csv_with_bom(self): sf = SFrame.read_csv(csvfile.name, header=True) self.assertEqual(sf.dtype, [float, int, str]) self.__test_equal(sf, df) + def test_read_json(self): + x='{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}' + sf=SFrame.read_json(x) + df =pd.read_json(x) + df=df.reset_index() + df=df.drop(['index'],axis=1) + self.__test_equal(sf, df) def test_auto_parse_csv(self): with tempfile.NamedTemporaryFile(mode='w', delete=False) as csvfile: