Can json.dumps create multiple lines

Cecil Westerhof Cecil at decebal.nl
Thu Dec 1 16:52:24 EST 2016


On Thursday  1 Dec 2016 17:55 CET, Zachary Ware wrote:

> On Thu, Dec 1, 2016 at 10:30 AM, Cecil Westerhof <Cecil at decebal.nl> wrote:
>> I would prefer when it would generate:
>> '[
>> "An array",
>> "with several strings",
>> "as a demo"
>> ]'
>>
>> Is this possible, or do I have to code this myself?
>
> https://docs.python.org/3/library/json.html?highlight=indent#json.dump
>
> Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) [GCC 4.2.1
> (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright",
> "credits" or "license" for more information.
>>>> import json
>>>> json.dumps(["An array", "with several strings", "as a demo"])
> '["An array", "with several strings", "as a demo"]'
>>>> print(_)
> ["An array", "with several strings", "as a demo"]
>>>> json.dumps(["An array", "with several strings", "as a demo"],
>>>> indent=0)
> '[\n"An array",\n"with several strings",\n"as a demo"\n]'
>>>> print(_)
> [
> "An array",
> "with several strings",
> "as a demo"
> ]

Works like a charm. Strings can contain newlines also, but then I do
not want a new line, but that works like a charm.

I used:
    cursor.execute('INSERT INTO test (json) VALUES (?)' ,
                   [json.dumps(['An array',
                                'with several strings',
                                'as a demo',
                                'and\none\nwith\na\nnewlines'],
                               indent = 0)])

and that gave exactly what I wanted.

Now I need to convert the database. But that should not be a big
problem.


> I've also seen something about JSON support in SQLite, you may want
> to look into that.

I will do that, but later. I have what I need.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof


More information about the Python-list mailing list