加载json数据时编码问题

时间:2014-10-30 17:25:30

标签: python json encoding

如何使用json模块加载此数据?看起来我需要再次学习一些编码讲座,解释会非常适合。

_json = """{"sku":"02366  20","productRef":"02366  20@1401-B1","image":"http://media.wuerth.com/stmedia/shop/348px/1337528.jpg","shortInfo":"Stahl verzinkt<br>SHR-BLA-(A2K)-M6X20","pdfCatalogPage":["http://media.wuerth.com/stmedia/shop/masterpages0000/LANG_de/03721.pdf"],"catalogSheet":"http://eshop.wuerth.de/stmedia/Blaetterkatalog/Gesamtkatalog/index.php?mode=or&searchquery=03721&hook_url=http://eshop.wuerth.de/-/","documentInfoMap":{},"cadValue":null,"showCadValue":null,"msdsInformations":[],"technicalInformation":"<table class=\"tech_table\"><tbody><tr><td class=\"tech_col_left\"><p>Nenndurchmesser</p></td><td class=\"tech_col_left\"><p>6 mm</p></td></tr><tr><td class=\"tech_col_left\"><p>Werkstoff</p></td><td class=\"tech_col_left\"><p>Stahl</p></td></tr><tr><td class=\"tech_col_left\"><p>Oberfläche</p></td><td class=\"tech_col_left\"><p>Verzinkt</p></td></tr><tr><td class=\"tech_col_left\"><p>Lochdurchmesser</p></td><td class=\"tech_col_left\"><p>8 mm</p></td></tr><tr><td class=\"tech_col_left\"><p>Länge</p></td><td class=\"tech_col_left\"><p>20 mm</p></td></tr><tr><td class=\"tech_col_left\"><p>Blattdicke</p></td><td class=\"tech_col_left\"><p>3 mm</p></td></tr></tbody></table>"}"""

print json.loads(_json, encoding='utf-8')

SyntaxError: Non-ASCII character '\xc3' in file

1 个答案:

答案 0 :(得分:2)

您需要在Python文件的顶部declare your encoding,并且您需要使用原始字符串文字,作为{{1} Python将其解释为普通\"字符:

"

以上假设您确实使用UTF-8作为源文件的编码;然后脚本产生:

# encoding: utf-8  
import json

_json = r"""
{"sku":"02366  20","productRef":"02366  20@1401-B1","image":"http://media.wuerth.com/stmedia/shop/348px/1337528.jpg","shortInfo":"Stahl verzinkt<br>SHR-BLA-(A2K)-M6X20","pdfCatalogPage":["http://media.wuerth.com/stmedia/shop/masterpages0000/LANG_de/03721.pdf"],"catalogSheet":"http://eshop.wuerth.de/stmedia/Blaetterkatalog/Gesamtkatalog/index.php?mode=or&searchquery=03721&hook_url=http://eshop.wuerth.de/-/","documentInfoMap":{},"cadValue":null,"showCadValue":null,"msdsInformations":[],"technicalInformation":"<table class=\"tech_table\"><tbody><tr><td class=\"tech_col_left\"><p>Nenndurchmesser</p></td><td class=\"tech_col_left\"><p>6 mm</p></td></tr><tr><td class=\"tech_col_left\"><p>Werkstoff</p></td><td class=\"tech_col_left\"><p>Stahl</p></td></tr><tr><td class=\"tech_col_left\"><p>Oberfläche</p></td><td class=\"tech_col_left\"><p>Verzinkt</p></td></tr><tr><td class=\"tech_col_left\"><p>Lochdurchmesser</p></td><td class=\"tech_col_left\"><p>8 mm</p></td></tr><tr><td class=\"tech_col_left\"><p>Länge</p></td><td class=\"tech_col_left\"><p>20 mm</p></td></tr><tr><td class=\"tech_col_left\"><p>Blattdicke</p></td><td class=\"tech_col_left\"><p>3 mm</p></td></tr></tbody></table>"}

"""

print json.loads(_json, encoding='utf-8')