-1

I am trying to write json in file by using Json.dump with python 3.X

here is the code :

#write in a file
with open('./mydata/dataleaf.json','w') as outfile:
    json.dump(leafdata["data"],outfile)

on my file the outut is :

["{\"Extracts\":[],\"NextPageUrl\":\"\",\"PageCount\":0}", "{\"Extracts\":[],\"NextPageUrl\":\"\",\"PageCount\":0}"]

What I would to get is :

['{"Extracts":[],"NextPageUrl":"","PageCount":0}',
 '{"Extracts":[],"NextPageUrl":"","PageCount":0}']

I have tried Eval() but still not working because I am trying to save list of string in file (not a single string) (python json dumps) . Thanks in advance

  • Possible duplicate of [python json dumps](https://stackoverflow.com/questions/15272421/python-json-dumps) – tripleee Nov 15 '18 at 10:28
  • 1
    You are reading in a string and dumping that string as the only member of a JSON list. If the string is JSON, you need to parse it back into Python if you want to process it, and if not, simply just print it out again as it is already in JSON format. – tripleee Nov 15 '18 at 10:30
  • In pseudocode, you are basically doing `print(json.dumps(json.dumps(data))` where you want `print(json.dumps(data))` or possibly simply `print(data)` – tripleee Nov 15 '18 at 10:31
  • When I try this with open('./mydata/dataleaf.json','w') as outfile: outfile.write(leafdata["data"]) I have this error : TypeError: write() argument must be str, not list – Leaf Leafword Nov 15 '18 at 10:36
  • Looks like `leafdata["data"][0]` would be the ticket here but obviously we can only speculate whether this will work in the more general case without more information about where this data comes from. – tripleee Nov 15 '18 at 10:39
  • leafdata["data"][0] worked , how to do with the list leafdata["data"] please? – Leaf Leafword Nov 15 '18 at 10:41
  • This is drifting from your original question. My suggestion at this point would be to *(1)* accept the duplicate nomination and *(2)* ask a new question with more and better details if you cannot figure it out from the duplicate's answers. – tripleee Nov 15 '18 at 10:42
  • Perhaps see also https://stackoverflow.com/questions/9138112/looping-over-a-list-in-python – tripleee Nov 15 '18 at 10:43

1 Answers1

0

It appear that leafdata["data"] is a list containing only one json-serialized data. Try this:

with open('./mydata/dataleaf.json','w') as outfile:
    outfile.write(leafdata["data"][0])

to write directly the content to your file, or if you need to modify the content before writing it:

with open('./mydata/dataleaf.json','w') as outfile:
    python_data = json.loads(leafdata["data"][0])
    # [...] do something with "python_data"
    json.dump(python_data, outfile)
Antwane
  • 18,008
  • 7
  • 43
  • 76