2

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"]

notpepsi
  • 23
  • 3
  • Does your string include `“` instead of `"`? – Boseong Choi Mar 17 '20 at 11:25
  • Hi @notpespi.Just to be clear, the nested lists we are seeing are inside a `str`, isn't it? Something like: `"""[[“a”,”bb”],[“c12”,”dddd”],[“and”,”so on”]]"""`. And the paticular quotes used are in the string o we find only _normal_ quotes (`"`) char? – Matteo Ragni Mar 17 '20 at 11:26
  • 1
    Please give us the expected result – azro Mar 17 '20 at 11:26
  • no my phone just style it so. I will correct it with my pc. – notpepsi Mar 17 '20 at 11:26
  • Does this answer your question? [How to make a flat list out of list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – quamrana Mar 17 '20 at 11:29

1 Answers1

2

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"}'
Matteo Ragni
  • 2,837
  • 1
  • 20
  • 34