Home > Back-end >  Which file is binary file type - Python?
Which file is binary file type - Python?

Time:06-12

I have to make an API call and fetch the json data in binary file type. For this I am using below code. For file output, I have referenced this 2 post: Post 1 and Post 2. My question is which of the below code contains JSON data in binary format ? I know mode 'wb' is writes data in binary format, but not sure if both the files are in binary format? Is there a way to verify which file is in Binary format ?

I am new to Python and API calling so help is much appreciated!

Thanks in advance!

Python

  import requests
    
    url = "https://covid-api.com/api/regions?iso=chn"
    
    payload={}
    headers = {}
    
    response = requests.request("GET", url, headers=headers, data=payload) 

Using Pickle module

 with open("file.pkl","wb") as f:
        pickle.dump(response.content, f)

Using JSON module

import json

with open("file.json","wb") as f:
    f.write(response.content)

CodePudding user response:

Use the requests response .json() method - whether that is binary is probably irrelevant as it will briefly be a native Python dict (which will almost-certainly be stuffed with utf-8 strings)

import json
import requests
r = requests.get(...)
r.raise_for_status()  # check if request succeeded
j = r.json()
with open(path_destination, "w") as fh:
    json.dump(j)
  • Related