简体   繁体   中英

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?

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

Try:

Import ast

json_= json.loads("raw string")

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

To convert it use json.loads(your_string_variable)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM