2

I have a site that I'm working on using Django that makes API requests to get information about cars. These requests are triggered by JS events, which go to a created URL that connects to a view. In my view, I make the actual API request and use the .json() method to get the returned JSON from the response.

What I'm having trouble doing however is getting a certain index/value from this response.

Here is an example of a response I would receive:

{
    "equipment": [{
        "id": "20047746549",
        "name": "Specifications",
        "equipmentType": "OTHER",
        "availability": "STANDARD",
        "attributes": [{
            "name": "Aerodynamic Drag (cd)",
            "value": "0.26"
        }, {
            "name": "Ege Highway Mpg",
            "value": "29"
        }, {
            "name": "Epa Combined Mpg",
            "value": "23"
        }, {
            "name": "Epa City Mpg",
            "value": "20"
        }, {
            "name": "Curb Weight",
            "value": "3957"
        }, {
            "name": "Turning Diameter",
            "value": "39.0"
        }, {
            "name": "Manufacturer 0 60mph Acceleration Time (seconds)",
            "value": "6.6"
        }, {
            "name": "Epa Highway Mpg",
            "value": "29"
        }, {
            "name": "Tco Curb Weight",
            "value": "3957"
        }, {
            "name": "Ege Combined Mpg",
            "value": "23"
        }, {
            "name": "Fuel Capacity",
            "value": "19.8"
        }, {
            "name": "Ege City Mpg",
            "value": "20"
        }]
    }],
    "equipmentCount": 1
}

What I'm trying to get is the "value": "3957" that corresponds to the "name": "Curb Weight" attribute

The way I thought about doing so (in Python) was jsonResponse['equipment'][0]['attributes'][4]['value'] however the index is not always the same for this Curb Weight attribute. Sometimes the index is 5, sometimes 6, etc.

Is there anyway to get this Curb Weight attribute, or any other attribute, by the value of it's "name" key?

Barmar
  • 741,623
  • 53
  • 500
  • 612
sidp
  • 147
  • 1
  • 2
  • 12
  • 1
    Loop over the array. Compare the name with what you're looking for, and then return the value. – Barmar Jun 28 '16 at 17:07
  • Wow, I feel stupid, lol. Thank you very much! – sidp Jun 28 '16 at 17:08
  • @MarcB That's not an array of objects. – Barmar Jun 28 '16 at 17:08
  • @sidp, do you have any control over the file format? The API could return a single dict instead of an array of dicts; each `name` attribute would be the key, and the `value` attribute would be the value. – Robᵩ Jun 28 '16 at 17:09
  • sort the list of dictionaries before you do the index: `jsonResponse['equipment'][0]['attributes'].sort(key=lambda attr: attr['name'])` – ritlew Jun 28 '16 at 17:10
  • @Robᵩ I don't unfortunately, this is the only format I can have the information returned as. – sidp Jun 28 '16 at 17:11

0 Answers0