Analizar JSON en Python


Mi proyecto está recibiendo actualmente un mensaje JSON en python del que necesito obtener bits de información. Para los propósitos de esto, vamos a establecerlo en un JSON simple en una cadena:

jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'

Hasta ahora he estado generando solicitudes JSON utilizando una lista y luego json.dumps pero para hacer lo contrario de esto creo que necesito usar json.loads pero no he tenido mucha suerte con ello. ¿Podría alguien proporcionarme un fragmento que devuelva "2 "con la entrada de" dos " en el ejemplo anterior?

Author: Kevin Guan, 2011-10-14

4 answers

Muy simple:

import json
j = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print j['two']
 345
Author: John Giotta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-14 17:05:26

A veces tu json no es una cadena. Por ejemplo, si obtiene un json de una url como esta:

j = urllib2.urlopen('http://site.com/data.json')

Necesitará usar json.carga, no json.cargas:

j_obj = json.load(j)

(es fácil de olvidar: la 's' es para 'string')

 67
Author: jisaacstone,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-14 17:09:50

Para URL o archivo, utilice json.carga(). Para tener cuerdas .contenido json, utilice json.carga().

#! /usr/bin/python

import json
from pprint import pprint

#json_file='a.json' 
json_file='my_cube.json'
cube='1'

json_data=open(json_file)
data = json.load(json_data)
#pprint(data)
json_data.close()

print "Dimension: ", data['cubes'][cube]['dim']
print "Measures:  ", data['cubes'][cube]['meas']
 33
Author: Mohammad Shahid Siddiqui,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-20 04:53:10

El siguiente es un ejemplo simple que puede ayudarlo:

json_string = """
{
    "pk": 1, 
    "fa": "cc.ee", 
    "fb": {
        "fc": "", 
        "fd_id": "12345"
    }
}"""

import json
data = json.loads(json_string)
if data["fa"] == "cc.ee":
    data["fb"]["new_key"] = "cc.ee was present!"

print json.dumps(data)

La salida para el código anterior será:

{"pk": 1, "fb": {"new_key": "cc.ee was present!", "fd_id": "12345", 
 "fc": ""}, "fa": "cc.ee"}

Tenga en cuenta que puede establecer el argumento ident de dump para imprimirlo de esta manera (por ejemplo,cuando se utiliza print json.vertederos (datos , indent=4)):

{
    "pk": 1, 
    "fb": {
        "new_key": "cc.ee was present!", 
        "fd_id": "12345", 
        "fc": ""
    }, 
    "fa": "cc.ee"
}
 21
Author: Venkat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-08 14:18:27