Convert string response into json or list

notpepsi :

My response look like:

"[["a","bb"],["c12","dddd"],["and","so on"]]"

So I tried with to convert this string with the list(response) but don’t got the result I wanted. Are there any simpler solutions to convert this response into a list or even json?

My expected result is a list like this: ["a", "bb", "c12", "dddd","and", "so on"]

Matteo Ragni :

If your string contains only basic literals (i.e. strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None), you can use the ast module to parse the string (ast.literal_eval):

import ast

in_str = """[["a","bb"],["c12","dddd"],["and","so on"]]"""
res_list = ast.literal_eval(in_str)

print(res_list)
# [['a','bb'],['c12','dddd'],['and','so on']]

From the documentation:

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

But you should also notice that:

It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.

If you need also to flat the resulting list you can follow the answer How to make a flat list out of list of lists?

One approach that I like from that post is something like:

import functools
import operators

flat_list = functools.reduce(operator.iconcat, res_list, [])
print(flat_list)
# ['a', 'bb', 'c12', 'dddd', 'and', 'so on'] 

With the information you gave us it is difficult to convert that string in a json representation, but one can try considering that you have a list of list of two elements. If we consider the two elements in the inner list as a (key, value) relation, it is possible to create a json-compatible dictionary in this way:

json_dict = dict(res_list)
print(json_dict)
# {'a': 'bb', 'c12': 'dddd', 'and': 'so on'}

import json
json.dumps(json_dict)
# '{"a": "bb", "c12": "dddd", "and": "so on"}'

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related