如何避免JSON percentencoding和\n escaping?

2024-05-14 08:44:36 发布

您现在位置:Python中文网/ 问答频道 /正文

当我解析文件时

<html>
    <head><meta charset="UTF-8"></head>
    <body><a href="Düsseldorf.html">Düsseldorf</a></body>
</html>

使用

^{pr2}$

我以\u转义结束

[{
    "name": "D\u00fcsseldorf",
    "url": "D\u00fcsseldorf.html"
}]

或者使用百分比编码字符串

D%C3%BCsseldorf

描述了hereitem exporter

# -*- coding: utf-8 -*-
import json
from scrapy.contrib.exporter import BaseItemExporter

class UnicodeJsonLinesItemExporter(BaseItemExporter):

    def __init__(self, file, **kwargs):
        self._configure(kwargs)
        self.file = file
        self.encoder = json.JSONEncoder(ensure_ascii=False, **kwargs)

    def export_item(self, item):
        itemdict = dict(self._get_serialized_fields(item))
        self.file.write(self.encoder.encode(itemdict) + '\n')

以及适当的饲料出口设置

FEED_EXPORTERS = {
    'json': 'myproj.exporter.UnicodeJsonLinesItemExporter',
}

不要帮忙。在

如何获得utf-8编码的JSON输出?在

我重申/扩展了一个unanswered question。在

更新

与刮片正交,注意没有设置

export PYTHONIOENCODING="utf_8"

跑步

> echo { \"name\": \"Düsseldorf\", \"url\": \"Düsseldorf.html\" } > dorf.json
> python -c'import fileinput, json;print json.dumps(json.loads("".join(fileinput.input())),sort_keys=True, indent=4, ensure_ascii=False)' dorf.json > dorf_pp.json

将失败

Traceback (most recent call last):
  File "<string>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 16: ordinal not in range(128)

更新

我的问题无法回答。UnicodeJsonLinesItemExporter正常工作,但管道的另一部分是罪魁祸首:作为一个漂亮地打印JSON输出的后处理,我使用的是python -m json.tool in.json > out.json。在


Tags: inimportselfjsonhtmlasciiitemhead
2条回答
>>> a = [{
    "name": "D\u00fcsseldorf",
    "url": "D\u00fcsseldorf.html"
}]
>>> a
[{'url': 'Düsseldorf.html', 'name': 'Düsseldorf'}]
>>> json.dumps(a, ensure_ascii=False)
'[{"url": "Düsseldorf.html", "name": "Düsseldorf"}]'

这似乎对我有用

# -*- coding: utf-8 -*-
import scrapy
import urllib

class SimpleItem(scrapy.Item):
    name = scrapy.Field()
    url = scrapy.Field()

class CitiesSpider(scrapy.Spider):
    name = "cities"
    allowed_domains = ["sitercity.info"]
    start_urls = (
        'http://en.sistercity.info/countries/de.html',
    )

    def parse(self, response):
        for a in response.css('a'):
            item = SimpleItem()
            item['name'] = a.css('::text').extract_first()
            item['url'] = urllib.unquote(
                a.css('::attr(href)').extract_first().encode('ascii')
                ).decode('utf8')
            yield item

使用你的问题中提到的饲料出口商,它也使用另一个存储

^{pr2}$

(必要时删除注释)

FEED_EXPORTERS = {
    'json': 'myproj.exporter.UnicodeJsonLinesItemExporter'
}
#FEED_STORAGES = {
#   '': 'myproj.exporter.CustomFileFeedStorage'
#}
FEED_FORMAT = 'json'
FEED_URI = "out.json"

相关问题 更多 >

    热门问题