Search code examples
pythonarcpy

Getting the date from customText from a json string


I'm trying to loop through this json string

"layoutOptions": {
    "titleText": "Route Number",
    "authorText": "West LA Yard",
    "copyrightText": "",
    "customTextElements": [{
            "Date": "9/11/2018, 7:37:35 AM"
        }
    ],
    "scaleBarOptions": {
        "metricUnit": "esriKilometers",
        "metricLabel": "km",
        "nonMetricUnit": "esriMiles",
        "nonMetricLabel": "mi"
    },
    "legendOptions": {
        "operationalLayers": [{
                "id": "ParcelRouteEditingTest_1458"
            }, {
                "id": "ParcelRouteEditingTest_1259"
            }
        ]
    }
}

I keep running to this error list indices must be integers, not str

layoutOpsDict = layoutData["layoutOptions"]
dateList = [dateEle["customTextElements"]["Date"] for dateEle in layoutOpsDict]

Error: Traceback (most recent call last):

  File "<pyshell#44>", line 1, in <module>
    dateList = [dateEle["customTextElements"]["Date"] for dateEle in layoutOpsDict]
TypeError: string indices must be integers, not str

What is the best method to grab the date in customTextElements other than keep setting more variables to keep track of?


Solution

  • You are looping through every key instead of just "customTextElements" and not all of them have a list of dictionaries with "Date" as the key.

    Since you only want to look through the values mapped to "customTextElements" you can only loop through that:

    dateList = [dateEle["Date"] for dateEle in layoutOpsDict["customTextElements"]]