{"id":1533,"date":"2014-10-24T15:53:40","date_gmt":"2014-10-24T15:53:40","guid":{"rendered":"http:\/\/ixyzero.com\/blog\/?p=1533"},"modified":"2014-10-24T15:53:40","modified_gmt":"2014-10-24T15:53:40","slug":"%e4%bd%bf%e7%94%a8python%e8%af%bb%e5%86%99%e5%8c%85%e5%90%ab%e4%b8%ad%e6%96%87%e7%9a%84json","status":"publish","type":"post","link":"https:\/\/ixyzero.com\/blog\/archives\/1533.html","title":{"rendered":"\u4f7f\u7528Python\u8bfb\u5199\u5305\u542b\u4e2d\u6587\u7684json"},"content":{"rendered":"<p>\u60f3\u8981\u8bfb\u5199\u4e2d\u6587json\uff0c\u53ef\u4ee5\u4f7f\u7528Python\u4e2d\u7684 json \u5e93\u53ef\u4ee5\u5bf9json\u8fdb\u884c\u64cd\u4f5c\u3002\u8bfb\u5165\u6570\u636e\u53ef\u4ee5\u4f7f\u7528 json.load\u3002<\/p>\n<p>f = open(fileName)\u00a0 #\u5efa\u8bae\u4f7f\u7528open()\u66ff\u4ee3file() <a href=\"http:\/\/stackoverflow.com\/questions\/6859499\/difference-between-python-file-operation-modules-open-and-file\" target=\"_blank\">http:\/\/stackoverflow.com\/questions\/6859499\/difference-between-python-file-operation-modules-open-and-file<\/a><\/p>\n<p>data = json.load(f)<\/p>\n<p>json\u683c\u5f0f\u7684\u6570\u636e\u88ab\u8f7d\u5165\u5230\u4e00\u4e2adict\u7c7b\u578b\u7684object\u5bf9\u8c61\u4e2d\u3002<\/p>\n<pre class=\"lang:default decode:true \">'''\nIn [5]: json.load??\nType:        function\nString form: &lt;function load at 0x0272DAB0&gt;\nFile:        c:python27libjson__init__.py\nDefinition:  json.load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)\nSource:\ndef load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,\n        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):\n'''<\/pre>\n<p>\u4f7f\u7528 json.dump \u53ef\u4ee5\u8f93\u51fajson\u3002\u4e0d\u8fc7\u8f93\u51fa\u7684\u6587\u672c\u5e76\u4e0d\u662f\u4e2d\u6587\uff0c\u800c\u662f\u8f6c\u6362\u4e3a utf-8\u7684\u683c\u5f0f\u3002\u6b64\u5904\u9700\u8981\uff1a<\/p>\n<pre class=\"lang:default decode:true\">json.dump(jsonData, targetFile, ensure_ascii=False, indent=4)<\/pre>\n<pre class=\"lang:default decode:true\">In [3]: import json\n\nIn [4]: json.dump??\nType:        function\nString form: &lt;function dump at 0x0272DA30&gt;\nFile:        c:python27libjson__init__.py\nDefinition:  json.dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, sort_keys=False, **kw)\nSource:\ndef dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,\n        allow_nan=True, cls=None, indent=None, separators=None,\n        encoding='utf-8', default=None, sort_keys=False, **kw):\n    \"\"\"Serialize ``obj`` as a JSON formatted stream to ``fp`` (a\n    ``.write()``-supporting file-like object).\n\n    If ``skipkeys`` is true then ``dict`` keys that are not basic types\n    (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)\n    will be skipped instead of raising a ``TypeError``.\n\n    If ``ensure_ascii`` is true (the default), all non-ASCII characters in the\n    output are escaped with ``uXXXX`` sequences, and the result is a ``str``\n    instance consisting of ASCII characters only.  If ``ensure_ascii`` is\n    ``False``, some chunks written to ``fp`` may be ``unicode`` instances.\n    This usually happens because the input contains unicode strings or the\n    ``encoding`` parameter is used. Unless ``fp.write()`` explicitly\n    understands ``unicode`` (as in ``codecs.getwriter``) this is likely to\n    cause an error.\n\n    If ``check_circular`` is false, then the circular reference check\n    for container types will be skipped and a circular reference will\n    result in an ``OverflowError`` (or worse).\n\n    If ``allow_nan`` is false, then it will be a ``ValueError`` to\n    serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)\n    in strict compliance of the JSON specification, instead of using the\n    JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).\n\n    If ``indent`` is a non-negative integer, then JSON array elements and\n    object members will be pretty-printed with that indent level. An indent\n    level of 0 will only insert newlines. ``None`` is the most compact\n    representation.  Since the default item separator is ``', '``,  the\n    output might include trailing whitespace when ``indent`` is specified.\n    You can use ``separators=(',', ': ')`` to avoid this.\n\n    If ``separators`` is an ``(item_separator, dict_separator)`` tuple\n    then it will be used instead of the default ``(', ', ': ')`` separators.\n    ``(',', ':')`` is the most compact JSON representation.\n\n    ``encoding`` is the character encoding for str instances, default is UTF-8.\n\n    ``default(obj)`` is a function that should return a serializable version\n    of obj or raise TypeError. The default simply raises TypeError.\n\n    If *sort_keys* is ``True`` (default: ``False``), then the output of\n    dictionaries will be sorted by key.\n\n    To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\n    ``.default()`` method to serialize additional types), specify it with\n    the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.\n\n    \"\"\"<\/pre>\n<p><strong>\u8f93\u51fa\u4e2d\u6587\u7684json<\/strong><strong>\u3002\u901a\u8fc7\u4f7f\u7528ensure_ascii=False<\/strong><strong>\uff0c\u8f93\u51fa\u539f\u6709\u7684\u8bed\u8a00\u6587\u5b57\u3002<\/strong>indent\u53c2\u6570\u662f\u7f29\u8fdb\u6570\u91cf\u3002<\/p>\n<p>\u66f4\u6539\u5199\u6587\u4ef6\u683c\u5f0f\uff1a\u5c06\u4e0a\u4e00\u6b65\u5bfc\u51fa\u7684 string \u76f4\u63a5\u5199\u6587\u4ef6\u4f1a\u62a5\u9519\uff08\u53ef\u80fd\u53ea\u5728Python2.7\u4e2d\u51fa\u73b0\uff09\uff1a<\/p>\n<p>UnicodeEncodeError: <span style=\"color: #ff0000;\">&#8216;ascii&#8217; codec can&#8217;t encode characters in position 1-9: ordinal not in range(128)<\/span><\/p>\n<p>\u8fd9\u662f\u7531\u4e8e\u6b64\u5904\u8f93\u51fa\u7684\u4e00\u4e9bascii\u7f16\u7801\u4e0d\u652f\u6301\uff0c\u6240\u4ee5\u62a5\u9519\u3002<\/p>\n<p><strong>\u89e3\u51b3\u7684\u529e\u6cd5\u662f\uff0c\u5728\u8f93\u51fa\u7684\u65f6\u5019\uff0c\u5bf9\u6587\u4ef6\u6307\u5b9a\u7279\u5b9a\u7684UTF-8<\/strong><strong>\u7f16\u7801<\/strong>\uff1a<\/p>\n<pre class=\"lang:default decode:true\">import codecs\nwith codecs.open(path_to_fileName, 'w', 'utf-8') as fp:\n    #write to fp\n'''\nIn [1]: import codecs\n\nIn [2]: codecs.open??\nType:        function\nString form: &lt;function open at 0x025A8C30&gt;\nFile:        c:python27libcodecs.py\nDefinition:  codecs.open(filename, mode='rb', encoding=None, errors='strict', buffering=1)\nSource:\ndef open(filename, mode='rb', encoding=None, errors='strict', buffering=1):\n...\n'''<\/pre>\n<pre class=\"lang:default decode:true \">#!\/usr\/bin\/env python\n# coding=utf-8\nimport json, codecs\n\nf_in = open('json.txt', 'r')\ndata_in = json.load(f_in)\nf_out = open('json_out.txt', 'w')\njson.dump(data_in, f_out, indent=4)\nf_out2 = codecs.open('json_out2.txt', 'w', 'utf-8')\njson.dump(data_in, f_out2, ensure_ascii=False, indent=4)<\/pre>\n<p>&nbsp;<\/p>\n<h6><strong>\u53c2\u8003\u94fe\u63a5\uff1a<\/strong><\/h6>\n<ul>\n<li><a href=\"https:\/\/docs.python.org\/2\/library\/json.html\" target=\"_blank\">https:\/\/docs.python.org\/2\/library\/json.html<\/a><\/li>\n<li><a href=\"http:\/\/www.songyang.net\/python-json\/\" target=\"_blank\">\u4f7f\u7528 python \u8bfb\u5199\u4e2d\u6587json<\/a><\/li>\n<li><a href=\"http:\/\/stackoverflow.com\/questions\/6859499\/difference-between-python-file-operation-modules-open-and-file\" target=\"_blank\">http:\/\/stackoverflow.com\/questions\/6859499\/difference-between-python-file-operation-modules-open-and-file<\/a><\/li>\n<li><a title=\"Python\u89e3\u6790json\u5b66\u4e60\" href=\"http:\/\/ixyzero.com\/blog\/archives\/368.html\" target=\"_blank\">Python\u89e3\u6790json\u5b66\u4e60<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>\u60f3\u8981\u8bfb\u5199\u4e2d\u6587json\uff0c\u53ef\u4ee5\u4f7f\u7528Python\u4e2d\u7684 json \u5e93\u53ef\u4ee5\u5bf9json\u8fdb\u884c\u64cd\u4f5c\u3002\u8bfb\u5165\u6570\u636e\u53ef\u4ee5\u4f7f\u7528 json [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7,12],"tags":[181,8],"class_list":["post-1533","post","type-post","status-publish","format-standard","hentry","category-programing","category-tools","tag-json","tag-python"],"views":8420,"_links":{"self":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/1533","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/comments?post=1533"}],"version-history":[{"count":0,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/1533\/revisions"}],"wp:attachment":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/media?parent=1533"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/categories?post=1533"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/tags?post=1533"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}