简体   繁体   中英

How to take two keys with a same name in JSON


The code below already takes "street": "Manhattan street 15" , but how I can take "PL 300" since they have the same name?

My current python code:

 contact_info = dict(business_id=business_id, 
                     name=business_info['name'], 
                     street=address['street'],
                     post_code=address['postCode'],
                     city=address['city'],
                     website=address['website'],
                     phone=address['phone'],
                     register_date=register_date
                    )

And this is the JSON format:

"addresses": [
  {
    "street": "Manhattan street 15",
    "postCode": "53100",
    "type": 1,
    "city": "Monaco",
    "country": "MC",
    "website": null,
    "phone": null,
    "fax": null,
    "registrationDate": "2014-11-17",
    "endDate": null
},
{
    "street": "PL 300",
    "postCode": "00089",
    "type": 2,
    "city": "Halic",
    "country": "Hc",
    "website": null,
    "phone": null,
    "fax": null,
    "registrationDate": "2014-11-17",
    "endDate": null
    }
]

The json you have posted its an array of object so you have to get the object from which you want to fetch the street

so var address=adresses[1]; street=address[street];

you can go through iteration

It is seemed address as a list with two dicts.So

address[0]['street'] #will give you street in first dict
address[1]['street'] #will give you street in second dict
import json    
business_info = json.loads('your.json')
streets = [address['street'] for address in business_info.address]

TRY:

from urllib2 import urllib
import json

url = 'http://example.com'
response = urlopen(url)
json_obj = json.load(response)

for i in json_obj['addresses']:
    print i['street']

It should work. It'll all the street names within addresses array.
For other values u need to specify those entity names like I did for street

It's a JSON array with two contacts, therefore json["address"][0]["street"] and json["address"][1]["street"] are different.

import json

contact_infos = []

parsed_json = json.loads(json_string)

for addr in parsed_json["addresses"]:
    contact_infos.append(
        dict(
            business_id=9999,
            name="Jason Derulo",
            street=addr["street"],
            post_code=addr["postCode"],
            city=addr["city"],
            website=addr["website"],
            phone=addr["phone"],
            register_date=addr["registrationDate"]
        )
    )

# A list of two contact infos                                                                                                     
print(contact_infos)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM