2011-11-22 21 views
8

Come posso scorrere il seguente file JSON e se fa = "cc.ee" quindi aggiungere un valore all'interno di fb?parsing json python

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


#!/usr/bin/env python 
import json,urllib 
json_data=open("my.json") 
data = json.load(json_data) 
for entry in data: 
    json.dumps(entry) 
json_data.close() 
exit 
+0

Si noti che il [JSON Validator] (http://jsonlint.com/) ha problemi con il tuo JSON. Valida se rimuovi le ultime due virgole (vedi 'json_string' nella risposta di Pablo). –

risposta

17

Gli oggetti JSON si comportano come dizionari. È possibile aggiungere un valore assegnando alla nuova chiave come si farebbe per un dizionario:

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) 
+3

Un'altra cosa del modulo 'json': per le versioni precedenti' simplejson' dovrebbe essere disponibile se 'json' non lo è. Facendo 'import simplejson come json' (' import json' se 'ImportError' è stato catturato) si può ottenere compatibilità con le versioni precedenti e possibilmente ricavare profitto dalle prestazioni ('simplejson' si dice che sia aggiornato più frequentemente). Entrambi i moduli hanno la stessa interfaccia, quindi vengono utilizzati allo stesso modo. Vedi di più in [questa domanda] (http://stackoverflow.com/questions/712791/json-and-simplejson-module-differences-in-python). – Tadeck