YUNO
YUNO

Reputation: 47

how to convert a raw string to a list in python3?

I want to convert a raw string to a list in python3.6

import json
from collections import OrderedDict

raw_string_list = "[{\"number\":1,\"url\":\"https:\\/\\/www.google.com\",\"content\":\"I\'am a a\"},{\"number\":2,\"url\":\"https:\\/\\/www.stackoverflow.com\",\"content\":\"I\'am a b\"}]"
json_dict = OrderedDict()
json_dict["content"] = list(raw_string_list)

with open("test.json", 'w', encoding="utf-8") as makefile:
    json.dump(json_dict, makefile, ensure_ascii=False)
makefile.close()

The json file I want is below.

{"content":[{"number":1,"url":"https://www.google.com","content":"'I'am a a"},{"number":2,"url":"https://www.stackoverflow.com","content":"'I'am a b"}]}

But the actual result is below.

{"content": ["[", "{", "\"", "n", "u", "m", "b", "e", "r", "\"", ":", "1", ",", "\"", "u", "r", "l", "\"", ":", "\"", "h", "t", "t", "p", "s", ":", "\\", "/", "\\", "/", "w", "w", "w", ".", "g", "o", "o", "g", "l", "e", ".", "c", "o", "m", "\"", ",", "\"", "c", "o", "n", "t", "e", "n", "t", "\"", ":", "\"", "I", "'", "a", "m", " ", "a", " ", "a", "\"", "}", ",", "{", "\"", "n", "u", "m", "b", "e", "r", "\"", ":", "2", ",", "\"", "u", "r", "l", "\"", ":", "\"", "h", "t", "t", "p", "s", ":", "\\", "/", "\\", "/", "w", "w", "w", ".", "s", "t", "a", "c", "k", "o", "v", "e", "r", "f", "l", "o", "w", ".", "c", "o", "m", "\"", ",", "\"", "c", "o", "n", "t", "e", "n", "t", "\"", ":", "\"", "I", "'", "a", "m", " ", "a", " ", "b", "\"", "}", "]"]}

How can I convert a raw string to a list and get the result I want?

Upvotes: 0

Views: 310

Answers (3)

abheet22
abheet22

Reputation: 470

Try:

Import ast

json_= json.loads("raw string")

ast.literal_eval({"content":json_})

Upvotes: 0

user11553043
user11553043

Reputation:

Try using json.loads(raw_string_list). That will convert a JSON-ic string to the cognate Python types :)

Upvotes: 1

BleuBizarre
BleuBizarre

Reputation: 378

To convert it use json.loads(your_string_variable)

At the moment you convert a string to a list > becomes a list of characters.

Upvotes: 0

Related Questions