0

I store some data in a excel that I extract in a JSON format. I also call some data with GET requests from some API I created. With all these data, I do some test (does the data in the excel = the data returned by the API?)

In my case, I may need to store in the excel the way to select the data from the API json returned by the GET.

for example, the API returns :

{"countries":
    [{"code":"AF","name":"Afghanistan"},
     {"code":"AX","name":"Åland Islands"} ...

And in my excel, I store :

excelData['countries'][0]['name']

I can retrieve the excelData['countries'][0]['name'] in my code just fine, as a string.

Is there a way to convert excelData['countries'][0]['name'] from a string to some code that actually points and get the data I need from the API json?

here's how I want to use it :

self.assertEqual(str(valueExcel), path) 
#path is the string from the excel that tells where to fetch the data from the
# JSON api

I thought strings would be interpreted but no :

AssertionError: 'AF' != "excelData['countries'][0]['code']"
- AF
+ excelData['countries'][0]['code']
fire frost
  • 427
  • 7
  • 23

1 Answers1

2

You are looking for the eval method. Try with this:

self.assertEqual(str(valueExcel), eval(path)) 

Important: Keep in mind that eval can be dangerous, since malicious code could be executed. More warnings here: What does Python's eval() do?

olinox14
  • 6,177
  • 2
  • 22
  • 39
  • `ast.literal_eval` is a safer alternative if you do some string splices, use `literal_eval` to get the dictionary keys than manually put that keys in the dictionary. It would require some string splicing but would be safer. Just another alternative. – Error - Syntactical Remorse Jun 18 '19 at 15:24
  • Thanks, never seen that method before. I plan to use that only for tests and only the admins can execute them. And quick note, it's on the `path ` variable that I needed the `eval`. – fire frost Jun 18 '19 at 16:03