Getting data (json) but saving as Str

Question:

I wrote a code with which I can call data from url every 5 secodns and save it in a csv file:

   import time

   run_time = 30
   run_until = time.time() + run_time
   while time.time() < run_until:
       url = 'http://xxx'
       csv_file = open('cam_data2.csv', 'a')
       req = requests.get(url)
       data = req.json()
       csv_file.write(str(data))     #here I have to concade the value to str
       csv_file.write('n')
       time.sleep(5)
       csv_file.close()

Now my problem is that I am working with this tipe of data:
{"blood_pressure_diastolic_value":70.0,"blood_pressure_systolic_value":120.0}

and the csv_file.write() method only allows me to save it as a string. Is there any other way that the json structure stays as it is so that I can later recall the value of each item?

Asked By: WonderWoman

||

Answers:

Although i would suggest to save it as json file instead of csv. But,if you still want to write to csv you can follow.

   import time
   import json



   run_time = 30
   run_until = time.time() + run_time
   while time.time() < run_until:
       url = 'http://xxx'
       csv_file = open('cam_data2.csv', 'a')
       req = requests.get(url)
       data = req.json()
       # dumps the data using json library
       csv_file.write(json.dumps(data)) 
       csv_file.write('n')
       time.sleep(5)
       csv_file.close()
Answered By: Atif
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.