<jupyter_start><jupyter_text>24 - Advanced Exercises*   JSON<jupyter_code># Run this cell to import the main class:
import json<jupyter_output><empty_output><jupyter_text>🍿🍿🍿1.Create a Python program that will convert a Python object to JSON data.<jupyter_code># Write your own code in this cell
myobj = {"_id":"e7bee06e34cf468399c3bf82d8e766f4",
            "cals_per100grams":"89",
            "category_id":"97e8f81e5c0a44bbbbd527d46477281b",
            "kj_per100grams":"374",
            "name":"Banana",
            "per100grams":"100",
            "in_the_market":True}

json_obj = 
print("\nJSON data:")
print(json_obj)<jupyter_output><empty_output><jupyter_text>🍿🍿🍿2.Create a Python code that will transform JSON data to Python objects.<jupyter_code># Write your own code in this cell
json_data = '{"cals_per100grams": "89", "kj_per100grams": "374", "name": "Banana"}'
myobj = 
print("Name: ", myobj[])
print("Calories per 100 grams: ", myobj[])
print("Kilojoules per hundred grams : ", myobj[])<jupyter_output><empty_output><jupyter_text>🍿🍿🍿3.Make a Python program that converts Python objects to JSON data.Print out all of the values.<jupyter_code># Write your own code in this cell
mydict =  {"cals_per100grams": "89", "kj_per100grams": "374", "name": "Banana"}
mylist =  ["Apple", "Orange", "Banana"]
mystr =  "Math doesn’t take sides. It doesn’t judge"
myint =  999_999_000_001
myfloat =  3.14159
mybool =  True
mynone =  None

json_obj =  
json_array =  
json_string =  
json_int_number =  
json_float_number =  
json_bool =  
json_null =  
print("json object : ", )
print("jason array : ", )
print("json string : ", )
print("json number1 : ", )
print("json number2 : ", )
print("json bool : ", )
print("json null ; ", )<jupyter_output><empty_output><jupyter_text>🍿4.Make a Python program that converts a Python dictionary (sorted alphabetically) to JSON data.Using indent level 4, print the object members. *(use sort_keys= and indent= )*Solve the same problem once more, but this time sort the objects by their scores. (use lambda to do this task)<jupyter_code># Write your own code in this cell

myobj = {'Zahra': 19, 'Ali': 18, 'Hassan': 13, 'Hossein': 20, }
print("Original Object:")
print(myobj)
print("\nJSON data:")
print()<jupyter_output><empty_output><jupyter_text>🍿🍿5.The Tehran weather prediction is kept in a JSON file at this location: **```"./Files/json/tehran.json"```** . Use this file and display the following output :```Tehran is Sunny on Thu Nov 18 06:30:00 2021.The minimum temperature is 39 degrees and and the maximum temperature is 52 degrees. Tehran is Mostly Sunny on Fri Nov 19 06:30:00 2021.The minimum temperature is 37 degrees and and the maximum temperature is 53 degrees. Tehran is Mostly Sunny on Sat Nov 20 06:30:00 2021.The minimum temperature is 42 degrees and and the maximum temperature is 56 degrees. Tehran is Partly Cloudy on Sun Nov 21 06:30:00 2021.The minimum temperature is 42 degrees and and the maximum temperature is 60 degrees. Tehran is Partly Cloudy on Mon Nov 22 06:30:00 2021.The minimum temperature is 46 degrees and and the maximum temperature is 58 degrees. Tehran is Partly Cloudy on Tue Nov 23 06:30:00 2021.The minimum temperature is 44 degrees and and the maximum temperature is 61 degrees. Tehran is Mostly Sunny on Wed Nov 24 06:30:00 2021.The minimum temperature is 41 degrees and and the maximum temperature is 61 degrees. Tehran is Partly Cloudy on Thu Nov 25 06:30:00 2021.The minimum temperature is 45 degrees and and the maximum temperature is 59 degrees. Tehran is Mostly Cloudy on Fri Nov 26 06:30:00 2021.The minimum temperature is 45 degrees and and the maximum temperature is 57 degrees. Tehran is Partly Cloudy on Sat Nov 27 06:30:00 2021.The minimum temperature is 41 degrees and and the maximum temperature is 56 degrees. Tehran is Partly Cloudy on Sun Nov 28 06:30:00 2021.The minimum temperature is 39 degrees and and the maximum temperature is 54 degrees. ```You can also use the following method to convert date to a more readable format: **```time.ctime(int("1637204400"))```** -->**'Thu Nov 18 06:30:00 2021'**<jupyter_code># Write your own code in this cell
import time<jupyter_output><empty_output><jupyter_text>🍿6.Complete the VectorEncoder class so that objects from the Vector Class can be serialized to JSON data as follows : ```[    {        "Vector(0, 0, 1, 1)": {            "x1": 0,            "y1": 0,            "x2": 1,            "y2": 1        }    },    {        "Vector(-1, 1, 1, -1)": {            "x1": -1,            "y1": 1,            "x2": 1,            "y2": -1        }    }]```<jupyter_code># Write your own code in this cell
class Vector(object):
    def __init__(self, x1, y1, x2, y2):
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
    def __repr__(self):
        return f'{self.__class__.__name__}({self.x1}, {self.y1}, \
{self.x2}, {self.y2})'
    
class VectorEncoder():
    pass

a = Vector(0, 0, 1, 1)
b = Vector(-1, 1, 1, -1)
myobj = [a, b]
json.dumps(myobj, cls=VectorEncoder, indent=4)<jupyter_output><empty_output><jupyter_text>🍿7.Complete the **```custom_decoder(obj)```** function so that the following JSON data after decoding gives us a complex number.<jupyter_code>j_data = '{"data": {"complex": {"__complex__": true, "real": 3.0, "imag": 4.0}}}'

def custom_decoder(obj):


x=json.loads(j_data, object_hook=custom_decoder)
print(x['data']['complex'])
type(x['data']['complex'])<jupyter_output><empty_output><jupyter_text>🍿🍿🍿8.Modify the text in the **```mytext```** variable, and then execute the next cell with your customized text.Then go to https://rapidapi.com/hub use the APIs there, and write your own applications using them.<jupyter_code>import requests

url = "https://google-translate1.p.rapidapi.com/language/translate/v2"
mytext = "The salt in the salt shaker has no salinity."
payload = "source=en&target=fa&q=" + mytext
headers = {
    'content-type': "application/x-www-form-urlencoded",
    'accept-encoding': "application/gzip",
    'x-rapidapi-host': "google-translate1.p.rapidapi.com",
    'x-rapidapi-key': "b06756d142msh2d78abbf6e25847p10ffa5jsna04de7af2118"
    }

response = requests.request("POST", url, data=payload, headers=headers)
json_data = response.text
myobj = json.loads(json_data)
print(myobj["data"]["translations"][0]["translatedText"])<jupyter_output>نمک موجود در نمکدان شوری ندارد.
{'fraction_non_alphanumeric': 0.12173777152680106, 'fraction_numerical': 0.06282231598687295, 'mean_word_length': 4.293631100082713, 'pattern_counts': {'":': 28, '<': 36, '<?xml version=': 0, '>': 37, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '622519', 'license': 'MIT', 'n_tokens_mistral': 2473, 'n_tokens_neox': 2108, 'n_words': 716, 'path': 'Exercise/24_PyEx.ipynb', 'repo_name': 'pytopia/PyExercises', 'size': '6399'}