Search code examples
pythonjsongoogle-visualizationpygooglechart

How to convert Google Charts Data Table into python dictionary?


I'm using the Google Visualization Library for python (gviz) to generate chart objects. This works great for generating JSON that can be read by the Google Charts using the DataTable.ToJSon method. What I'm trying to do now, however, is add multiple Google Chart data tables to one JSON dictionary. In other words, what I'm making now is this:

Chart_Data = JSON_Chart_Data_1

and what I want to make is this:

Chart_Data = {'Chart_1' : JSON_Chart_Data_1,
              'Chart_2' : JSON_Chart_Data_2,}

Where Chart_Data is converted into a JSON string in both cases.

I'm pretty sure I can do this by converting the JSON string from gviz back into a python dictionary, compile the strings in a container dictionary as necessary, and then convert that container dictionary back into JSON, but that doesn't seem like a very elegant way to do it. Is there a better way? What I'm picturing is a .ToPythonObject method equivalent to .ToJSon, but there doesn't appear to be one in the library.

Thanks a lot, Alex


Solution

  • I ended up doing my original, inelegant, solution to the problem with this function:

    def CombineJson(JSON_List):
          #Jsonlist should be a list of tuples, with the dictionary key and the json file to go with that.
          #eg: [('json1', 'some json string'), ('json2', 'some other json string')]
          Python_Dict = {}
          for tup in JSON_List:
                parsed_json = json.loads(tup[1])
                Python_Dict[tup[0]] = parsed_json
          BigJson = json.dumps(Python_Dict)
          return BigJson
    

    Thanks guys, Alex