-1

I had a json file, which I have converted to Dictionary. Based on the instructions I will generate a flow.

My json looks something like this:

   {
        "text":"Please tell me your first name",
        "var":"first_name"
    },
    {
        "calculated_variable":"True",
        "formula":"[]",
        "var":"rows"
    },
    {
        "text":"Enter the first row of the matrix.",
        "var":"rows[0]"
    }

So what I have to do is based on text user will enter a value. lets say for first block User entered "james". So "James" should be stored as first_name i.e first_name = "james".

Similarly considering the last block:

value should be stored as : row[0] = user_input

How will I make the "first_name" and "rows[0]" as variables as I have written above?

  • 1
    Possible duplicate of [Using python's eval() vs. ast.literal\_eval()?](https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval) (with slight modifications, if you need to convert a string representing you're desired variable into a actual variable) – Torxed Mar 01 '19 at 17:58
  • 2
    Are you trying to generate Python code *from* the JSON? Why? Why not just use a `dict`: `d = {}; d['first_name'] = 'James'; d['rows'][0] = ...`, etc. (Granted, that requires a string like `rows[0]` to be parsed a bit first, but there are probably other ways to work around that. – chepner Mar 01 '19 at 17:59
  • No I have converted it to dictionary. But I need the values to be stored in the specified variables as mentionaed inside the blocks. Because later I will be executing few formulae using the variables like: { "calculated_variable":"True", "formula":"[map(int, i.split()) for i in row]", "var":"matrix" }, here the before assigned variable "row" is being used. where i will be using eval() to do it – Kamal Panigrahi Mar 01 '19 at 18:13
  • https://stackoverflow.com/questions/19122345/to-convert-string-to-variable-name – Abolfazl Mar 01 '19 at 19:05

1 Answers1

0

I am not sure if it is the right way you would solve your problem, but you could add your values directly to your local namespace

>>> locals()['first_name'] = "James"
>>> first_name
James

locals() gives you the local namesspace.

stefan
  • 188
  • 1
  • 7
  • How will it help for a list? Like rows[1] ? – Kamal Panigrahi Mar 02 '19 at 03:42
  • ```locals()["rows"][1] = "James"``` if `rows` is already a list or `locals()["rows"] = ["James"]` if you want to create a list. `locals()["x"]` gives you the same object than just accesing the variable `x` – stefan Mar 02 '19 at 09:25