0

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?

YUNO
  • 47
  • 4
  • 1
    Is this what you are looking for ? https://stackoverflow.com/questions/4917006/string-to-dictionary-in-python – BleuBizarre Oct 07 '19 at 19:18
  • That is not a "raw string", which is a type of string literal. You have a string literal that represents a `list` literal. Usually, that's just a bad sign, but you can use `eval` (or more safely, `ast.literal_eval`) to evaluate the string as a python expression. – juanpa.arrivillaga Oct 07 '19 at 19:18
  • @YUNO `json_dict = {'content': json.loads(raw_string_list)}` will do the trick no need for ordered dict or to convert you variable to list. – Charif DZ Oct 07 '19 at 19:31

3 Answers3

1

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

0

Try:

Import ast

json_= json.loads("raw string")

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

abheet22
  • 470
  • 4
  • 12
  • `{"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"}]}` Can't I switch to "https://www.stackoverflow.com" instead of "https:\\/\\/www.stackoverflow.com"? – YUNO Oct 07 '19 at 19:27
  • Edited @YUNO, check now – abheet22 Oct 07 '19 at 19:41
0

To convert it use json.loads(your_string_variable)

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

BleuBizarre
  • 368
  • 2
  • 15