bhoomeendra
bhoomeendra

Reputation: 197

How to convert a list of Json string to Json Array in Python?

I have a list which is like

DecomposeTables = ['{ attr:["C", "A", "B"],fds:[[["A"], ["A"]], [["C"], ["B"]]],normalForm:"BCNF",pid:1,id:13, }', '{ attr:["C", "A", "B"],fds:[[["A"], ["A"]], [["C"], ["B"]]],normalForm:"BCNF",pid:1,id:13, }', '{ attr:["C", "A", "B"],fds:[[["A"], ["A"]], [["C"], ["B"]]],normalForm:"BCNF",pid:1,id:13, }']

i want to send it as json for api response i have tried

jsonpickle.encode(DecomposeTables,unpicklable=False)

but on front end i am reciving only one object as json other are null

data: 
["{ attr:["C", "B", "A"],fds:[[["A"], ["A"]], [["C"], ["B"]]],normalForm:"BCNF",pid:1,id:6, }", "{ attr:["C", "B", "A"],fds:[[["A"], ["A"]], [["C"], ["B"]]],normalForm:"BCNF",pid:1,id:6, }", "{ attr:["C", "B", "A"],fds:[[["A"], ["A"]], [["C"], ["B"]]],normalForm:"BCNF",pid:1,id:6, }"]

Upvotes: 0

Views: 1381

Answers (1)

user3456014
user3456014

Reputation:

Picking up from the comments.... assuming that you can put the keys in quotes.

(I'm using Python 3.8.1)

import ast
import json

# Note "attr" not attr, and so on.
# Each string is actually a string representation of a Python dictionary.
DecomposeTables = [
    '{ "attr":["C", "A", "B"],"fds":[[["A"], ["A"]], [["C"], ["B"]]],"normalForm":"BCNF","pid":1,"id":13 }', 
    '{ "attr":["C", "A", "B"],"fds":[[["A"], ["A"]], [["C"], ["B"]]],"normalForm":"BCNF","pid":1,"id":13 }', 
    '{ "attr":["C", "A", "B"],"fds":[[["A"], ["A"]], [["C"], ["B"]]],"normalForm":"BCNF","pid":1,"id":13 }'
    ]

# https://docs.python.org/3/library/ast.html => safely evaluate each string as a Python dictionary
as_dicts = [ast.literal_eval(x) for x in DecomposeTables]

# Now as_dicts is a Python list with Python dictionaries in it.
# You might be able to just send that object with Flask,
# but as an example here I'm writing the list as a json string
as_json = json.dumps(as_dicts)
print(as_json)

gives

[{"attr": ["C", "A", "B"], "fds": [[["A"], ["A"]], [["C"], ["B"]]], "normalForm": "BCNF", "pid": 1, "id": 13}, {"attr": ["C", "A", "B"], "fds": [[["A"], ["A"]], [["C"], ["B"]]], "normalForm": "BCNF", "pid": 1, "id": 13}, {"attr": ["C", "A", "B"], "fds": [[["A"], ["A"]], [["C"], ["B"]]], "normalForm": "BCNF", "pid": 1, "id": 13}]

Upvotes: 1

Related Questions