简体   繁体   中英

Python) How to convert string to dict? (Strange type of string)

The string is..

{
   "version":"20131101",
   "logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif",
   "title":"알라딘 베스트셀러 리스트 - 철학사",
   "link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&BranchType=1&CID=51441&Year=2019&Month=5&Week=4&partner=openAPI",
   "pubDate":"Mon, 27 May 2019 10:33:33 GMT",
   "totalResults":955,
   "startIndex":1,
   "itemsPerPage":10,
   "query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4",
   "searchCategoryId":51441,
   "searchCategoryName":"철학사",
   "item":[
      {
         "title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음",
         "link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&partner=openAPI&start=api",
         "author":"안광복 (지은이)",

      }
   ]
}

I wanna convert string to dict.

This is what I want

  1. I want to make this whole string to dictionary, So I want to get the value of "item"

     "item" : [{"title: ", " : ", ... }, {"title: ", " : ", ... }, { "title: ", " : ", ... }] 
  2. I want the dictionaries(looks like dictionary but string) in the list(looks like list but str) so i want to use like dictionary

     print(decoding_bestseller.find("item",370)) b=decoding_bestseller.split('"item"') want_str=b[1] want_str1=want_str.strip(':[]{}') want_list=want_str1.split(',') book_dic = {} for i in range(0,len(want_list)): in_colon = ":" in want_list[i] if in_colon: split_list = want_list[i].split(':') book_key = split_list[0].strip('""') book_value = split_list[1].strip('""') book_dic[book_key] = book_value 

I did like that but I failed.

The string is like this {" : ", " : ", "item : [ {"title : ", "link : ", } {"title : ", "link : ", }, " : "}

i want to make {"title : ", "link : ", ...} to REAL dictionary!

如果您的字符串写得很好(没有json错误,您可以在此处检查以更正json),则可以使用json.loads(yourString)doc

You can create a dictionary from a string using eval .

as_string = str({"version":"20131101","logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif","title":"알라딘 베스트셀러 리스트 - 철학사","link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&BranchType=1&CID=51441&Year=2019&Month=5&Week=4&partner=openAPI","pubDate":"Mon, 27 May 2019 10:33:33 GMT","totalResults":955,"startIndex":1,"itemsPerPage":10,"query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4","searchCategoryId":51441,"searchCategoryName":"철학사","item":[{"title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음","link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&partner=openAPI&start=api","author":"안광복 (지은이)",}]})
as_dict = eval(as_string)

Format of string you've provided is JSON. There's json module in python, which has function loads() . This function will convert your string to dict object.

But there's one problem in string you provided:

"author":"안광복 (지은이)" >>>,<<< }]}

This coma violates JSON stardart and causes error in decoder. If it's just typo, than just delete it. If source string really contains this, you should delete it from string before decoding (ig string.replace(",}", "}") )

How to decode:

import json

string = """{
   "version":"20131101",
   "logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif",
   "title":"알라딘 베스트셀러 리스트 - 철학사",
   "link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&amp;BranchType=1&amp;CID=51441&amp;Year=2019&amp;Month=5&amp;Week=4&amp;partner=openAPI",
   "pubDate":"Mon, 27 May 2019 10:33:33 GMT",
   "totalResults":955,
   "startIndex":1,
   "itemsPerPage":10,
   "query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4",
   "searchCategoryId":51441,
   "searchCategoryName":"철학사",
   "item":[
      {
         "title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음",
         "link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&amp;partner=openAPI&amp;start=api",
         "author":"안광복 (지은이)"
      }
   ]
}"""

object_from_string = json.loads(string)

value_of_item = object_from_string["item"]

for value in value_of_item:
    for k, v in value.items():
        print(f"{k} = {v}")

Output:

title = 처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음
link = http://www.aladin.co.kr/shop/wproduct.aspx?ItemId=100442130&amp;partner=openAPI&amp;start=api
author = 안광복 (지은이)

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