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']

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.