TomSelleck
TomSelleck

Reputation: 6968

Unable to append object to nested list

I have a JSON object which looks like this:

[
  {
    "modulename": "module1",
    "functions": [
      {
        "functionname": "get",
        "function": "function1"
      },
      {
        "functionname": "delete",
        "function": "function2"
      }
    ]
  }
]

My code looks like this:

modules = []

for functionname in function_dictionary:

    modulename = function_dictionary[function][1]
    func = function_dictionary[function][0]


    module_func = {"modulename" : modulename, "functions" : [{"functionname" : functionname, "function" : func}]}

    found = False
    for module in modules:
        if module["modulename"] == modulename:
            module["modulename"]["functions"].append({"functionname" : functionname, "function" : func}) #error here
            found = True
            break

    if not found:
        modules.append(module_func)

However I keep getting the string indices must be integers, not str error.

I'm not sure why I'm getting this.

I read it as "append the object {"functionname" : function, "function" : func} to the list located at module["modulename"]["functions"]

Any advice is apprciated!

Upvotes: 0

Views: 37

Answers (1)

TomSelleck
TomSelleck

Reputation: 6968

Silly me, was a typo on my part:

module["modulename"]["functions"].append({"functionname" : functionname, "function" : func}) #error here

Should have been:

module["functions"].append({"functionname" : function, "function" : func})

I was misreading my own object and though that the functions list was nested inside modulename when in fact they were at the same level.

Upvotes: 1

Related Questions