Last active
August 26, 2019 18:41
-
-
Save l337quez/c817f822c92bac2dfa815d80efd83b05 to your computer and use it in GitHub Desktop.
Todo en JSON, estoy trabajando con sokects y necesitaba usar un arreglo en JSON, puedes aprender a como convertir diccionarios a json, a bytes...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
#creamos un diccionario en python | |
print ("Diccionario de python:") | |
mensaje = {"carga1": True, "carga2": False, "carga3": True, "carga4": True , "corriente1": 3.5, "corriente2": 0,"corriente3": 0,"corriente4": 0} | |
print (mensaje) | |
print ("Tipo de variable:") | |
print (type(mensaje)) | |
print ("===============================================================") | |
#Serializamos el dicctionrio | |
print ("\n" "Convertiendo Diccionario a JSON") | |
msg = json.dumps(mensaje) | |
print ("Diccionario Serializado:") | |
print (msg) | |
print ("Pintando el Diccionario mas bonito:") | |
#con json.dumps convertimos de diccionario a json | |
print(json.dumps(mensaje, sort_keys=2, indent=4)) | |
print ("Tipo de variable:") | |
print (type(msg)) | |
print ("===============================================================") | |
#llevando a bytes | |
print ("\n" "Convertiendo JSON a bytes object") | |
msg_bytes = str.encode(msg) | |
print(msg_bytes) | |
print ("Tipo de variable:") | |
print (type(msg_bytes)) | |
print ("Convirtiendo de bytes a string:") | |
msg_bytes = msg_bytes.decode() | |
print(msg_bytes) | |
print ("Tipo de variable:") | |
print (type(msg_bytes)) | |
print ("===============================================================") | |
#Desserializamos el json | |
print ("\n" "Convertiendo JSON a Diccionario") | |
print ("Diccionario Serializado:") | |
data='[null, true, false, "Hola, mundo!"]' | |
msg= json.loads(data) | |
print (data) | |
print ("Pintando el Json mas bonito:") | |
print (json.dumps(data, indent=2)) | |
#dict_string = pformat(data) | |
#formatted_code, _ = FormatCode(dict_string) | |
#print (formatted_code) | |
#print(json.loads(data), sort_keys=False, indent=4) | |
print ("Tipo de variable:") | |
print (type(data)) | |
print ("===============================================================") | |
#NOTA: se puede cambiar el valor del sort e ident.. | |
#Diccionarios y JSON | |
#Si bien el resultado es prácticamente similar, existen algunas diferencias. Por ejemplo, en Python se | |
#usa None para indicar un valor vacío o no establecido, pero en JSON se emplea null. Python permite | |
#comillas simples, JSON requiere comillas dobles. En Python los valores booleanos son True y False; en JSON, true y false. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment