0

Hello guys I have this list from json post: The Json:

{"Array":"[(1, 2), (1, 3), (2, 3), (3, 4), (3, 5), (4, 5), (4, 6), (5, 6), (6, 7)]"}

I need to transform it in this format:

type<class 'list'>
[(1, 2), (1, 3), (2, 3), (3, 4), (3, 5), (4, 5), (4, 6), (5, 6), (6, 7)]

What i have tried:

def getData():
    json_data = request.get_json()
    newList=[]
    [newList.extend([v]) for k,v in json_data.items()]
    print("type:",type(newList))
    # OUTPUT: <class 'list'>
    print("list:",newList)
    # OUTPUT:['[(1, 2), (1, 3), (2, 3), (3, 4), (3, 5), (4, 5), (4, 6), (5, 6), (6, 7)]']
    print("type 1:",type(newList[0]))
    # OUTPUT:<class 'str'>
    print("list 1 :",newList[0])
    # OUTPUT:[(1, 2), (1, 3), (2, 3), (3, 4), (3, 5), (4, 5), (4, 6), (5, 6), (6, 7)]

In the first its a list but not in the format that i need, in the second its not a list but its in the format that i need.

Thanks for help!

Peter
  • 5
  • 6
  • use `ast.literal_eval` – ThePyGuy Jun 16 '21 at 11:24
  • 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) – mkrieger1 Jun 16 '21 at 11:38

2 Answers2

0

I'm gonna get downvotes for using exec. So I highly discourage usage of exec. But, here is a hack that works:

import json

jsonStr =  '{"Array":"[(1, 2), (1, 3), (2, 3), (3, 4), (3, 5), (4, 5), (4, 6), (5, 6), (6, 7)]"}'
jsonObj = json.loads(jsonStr)
exec("newList = "+jsonObj["Array"])

print(type(newList))
print(newList)
Joshua
  • 551
  • 4
  • 13
0

I think this might be what you are looking for.

import ast
data = {"Array":"[(1, 2), (1, 3), (2, 3), (3, 4), (3, 5), (4, 5), (4, 6), (5, 6), (6, 7)]"}
print(ast.literal_eval(data["Array"]))

prints:

[(1, 2), (1, 3), (2, 3), (3, 4), (3, 5), (4, 5), (4, 6), (5, 6), (6, 7)]

For more information about abstract syntax trees (ast) and literal_eval I refer you to the python docs: https://docs.python.org/3/library/ast.html

docPersson
  • 83
  • 5