문제

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

도움이 되었습니까?

해결책

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)))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top