Skip to content

BUG: Fix for json lines issue with backslashed quotes #14693

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 13 commits into from
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.19.2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ Bug Fixes
- Bug in clipboard functions on Windows 10 and python 3 (:issue:`14362`, :issue:`12807`)
- Bug in ``.to_clipboard()`` and Excel compat (:issue:`12529`)


- Bug in to_json with lines=true containing backslashed quotes (:issue:`14693`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.to_json() with lines=True specified, containing .....




Expand Down
6 changes: 4 additions & 2 deletions pandas/io/tests/json/test_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -962,9 +962,11 @@ def test_to_jsonl(self):
expected = '{"a":1,"b":2}\n{"a":1,"b":2}'
self.assertEqual(result, expected)

df = DataFrame([["foo}", "bar"], ['foo"', "bar"]], columns=['a', 'b'])
df = DataFrame([["foo}", "bar"], ['foo"', "bar"], ['foo\\', "bar"]],
columns=['a', 'b'])
result = df.to_json(orient="records", lines=True)
expected = '{"a":"foo}","b":"bar"}\n{"a":"foo\\"","b":"bar"}'
expected = ('{"a":"foo}","b":"bar"}\n{"a":"foo\\"","b":"bar"}\n'
'{"a":"foo\\\\","b":"bar"}')
self.assertEqual(result, expected)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In [5]: df.to_json(lines=True,orient='records')
Out[5]: '{"a":"foo}","b":"bar"}\n{"a":"foo\\"","b":"bar"}\n{"a":"foo\\\\","b":"bar"}'

is on current master. what is different?

assert_frame_equal(pd.read_json(result, lines=True), df)

Expand Down
6 changes: 4 additions & 2 deletions pandas/lib.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1111,8 +1111,10 @@ def convert_json_to_lines(object arr):
length = narr.shape[0]
for i in range(length):
v = narr[i]
if v == quote and i > 0 and narr[i - 1] != backslash:
in_quotes = ~in_quotes
if v == quote:
if not (i > 0 and narr[i - 1] == backslash and
i + 1 < length and narr[i + 1] != comma):
in_quotes = ~in_quotes
if v == comma: # commas that should be \n
if num_open_brackets_seen == 0 and not in_quotes:
narr[i] = newline
Expand Down