Pergunta

I have a list of dictionaries, How do I dump it using JSON one line per dictionary?

I tried:

json.dump( d, open('./testing.json','w'), indent=0)

where d is the list of dictionaries. But this newlines every (key,value) pair. I want each dictionary in one line. How should I do this?

Thanks

Foi útil?

Solução

You could turn it into a string with that format before writing it out. This could be done with a combination of a list comprehension and a join:

strs = [json.dumps(innerdict) for innerdict in d]
s = "[%s]" % ",\n".join(strs)
open('./testing.json','w').write(s)

In one line:

open('./testing.json','w').write("[%s]" % ",\n ".join(json.dumps(e) for e in d))

or:

open('./testing.json','w').write("[%s]" % ",\n ".join(map(json.dumps, d)))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top