1

in this code variable "r" consist of JSON array. how to access only the attribute company using the python code. for example, the result must be "Apple, Inc."

import pprint
import requests

MAC_URL = 'http://macvendors.co/api/%s'

r = requests.get(MAC_URL % 'BC:92:6B:A0:00:01')

pprint.pprint(r.json())

Result:

{'result': {'address': '1 Infinite Loop Cupertino CA US 95014 ',

        'company': 'Apple, Inc.',

        'mac_prefix': 'BC:92:6B'}}
jreznot
  • 2,694
  • 2
  • 35
  • 53
ADKD
  • 43
  • 8

3 Answers3

0

Your JSON is a list with dictionary inside . Take the dictionary part. Then you can access value for key: "company". To know how to take out dictionary from list, refer Converting JSON String to Dictionary Not List

You can also use https://docs.python.org/3/library/json.html

deosha
  • 972
  • 5
  • 20
0

Use the json library to turn this into a dictionary, and then you can acccess the company value by referencing the outer 'result' key and then the inner 'company' key.

from json import dump
response_dict = json.dump(r.json())
company = response_dict['result']['company']

https://docs.python.org/3/library/json.html

foobarbaz
  • 508
  • 1
  • 10
  • 27
0
import requests
import json
MAC_URL = 'http://macvendors.co/api/%s'
r = requests.get(MAC_URL % 'BC:92:6B:A0:00:01')
response_dict = json.loads(json.dumps(r.json()))
company = response_dict['result']['company']
print(company)
ADKD
  • 43
  • 8