-1

I have a 2 dimensional array, but the array is in a stringyfied form. I would like to convert it back to a python object so I can access the context

stringedArray = "[[4.50000e+01, 2.24000e+02, 1.70000e+02, 3.46000e+02, 9.40884e-01, 0.00000e+00],
        [2.91000e+02, 0.00000e+00, 4.69000e+02, 5.90000e+01, 9.19830e-01, 2.00000e+00],
        [4.71000e+02, 1.20000e+01, 5.22000e+02, 9.20000e+01, 9.04654e-01, 1.00000e+00],
        [1.93000e+02, 6.90000e+01, 2.64000e+02, 1.35000e+02, 8.95800e-01, 1.00000e+00],
        [1.80000e+01, 1.13000e+02, 1.29000e+02, 1.79000e+02, 8.90799e-01, 0.00000e+00],
        [9.90000e+01, 1.39000e+02, 2.78000e+02, 2.09000e+02, 2.62809e-01, 2.00000e+00]]"

 arrayObject = #convertion code here

 print(arrayObject[3][5])
 # prints: 1 or 1.00000

Is there a function in python similar to javascripts JSON.parse which converts a string to a object?

DrakeJest
  • 225
  • 3
  • 13
  • Does this answer your question? [How to convert string representation of list to a list?](https://stackoverflow.com/questions/1894269/how-to-convert-string-representation-of-list-to-a-list) – buran May 17 '22 at 05:58
  • Also https://stackoverflow.com/q/1894269/4046632 – buran May 17 '22 at 05:59

1 Answers1

0
from json import loads
stringed_list = "[[1, 2], [3, 4]]"
as_list = loads(stringed_list)
print(type(as_list)) # <class 'list'>
print(as_list[0][0]) # 1

edited according to comments. If you're working with a file, use json.load(file) instead.

VideoCarp
  • 35
  • 1
  • 2
  • 7
  • 1
    Please, don't suggest `eval` for that. Use either `json.loads()` (if working with string literal) or `json.load()` for working directly with file or `ast.literal_eval()`. – buran May 17 '22 at 06:47
  • OP sample is valid json, i.e. no need to "make it valid JSON" – buran May 17 '22 at 06:51