译(三十六)-Python读取json数据

stackoverflow热门问题目录

如有翻译问题欢迎评论指出,谢谢。

为什么 Python 无法解释 json 数据?

  • michele asked:

    • 文件里面有 json 如下:

    • {
      "maps": [
          {
              "id": "blabla",
              "iscategorical": "0"
          },
          {
              "id": "blabla",
              "iscategorical": "0"
          }
      ],
      "masks": [
          "id": "valore"
      ],
      "om_points": "value",
      "parameters": [
          "id": "valore"
      ]
      }
    • 然后我写了脚本来打印所有 json 数据:

    • import json
      from pprint import pprint
      with open('data.json') as f:
      data = json.load(f)
      pprint(data)
    • 但程序报错了:

    • Traceback (most recent call last):
      File "", line 5, in 
      data = json.load(f)
      File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
      return _default_decoder.decode(s)
      File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
      obj, end = self.raw_decode(s, idx=_w(s, 0).end())
      File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode
      obj, end = self.scan_once(s, idx)
      json.decoder.JSONDecodeError: Expecting ',' delimiter: line 13 column 13 (char 213)
    • 怎么才能解释 json,并从中取值?

  • Answers:

    • Justin Peel - vote: 2187

    • 这串数据并不是有效的 JSON 格式,有的 [] 应该是 {} :

      • [] 是 json 数组,对应 Python 的 list
      • {} 是 json 对象,对应 Python 的 dict
    • 正确的 json 应该是这样的:

    • {
        "maps": [
            {
                "id": "blabla",
                "iscategorical": "0"
            },
            {
                "id": "blabla",
                "iscategorical": "0"
            }
        ],
        "masks": {
            "id": "valore"
        },
        "om_points": "value",
        "parameters": {
            "id": "valore"
        }
      }
    • 然后是代码:

    •   import json
        from pprint import pprint
        with open('data.json') as f:
            data = json.load(f)
        pprint(data)
    • 对于这些数据,可以这样获取值:

    • data["maps"][0]["id"]
      data["masks"]["id"]
      data["om_points"]
    • 试试,看看是不是正常了。

    • Bengt - vote: 320

      • data.json 应该是这样的:

      • {
        "maps":[
             {"id":"blabla","iscategorical":"0"},
             {"id":"blabla","iscategorical":"0"}
            ],
        "masks":
             {"id":"valore"},
        "om_points":"value",
        "parameters":
             {"id":"valore"}
        }
      • 代码应该是这样的:

      • import json
        from pprint import pprint
        with open('data.json') as data_file:    
        data = json.load(data_file)
        pprint(data)
      • 注意这只在 Python 2.6 及以上版本可用,因为它依赖于 with 。在 Python 2.5 使用 from __future__ import with_statement ,对于 Python 2.4 以下的版本,见 Justin Peel 的回答

      • 这样可以获取单个值:

      • data["maps"][0]["id"]  # will return 'blabla'
        data["masks"]["id"]    # will return 'valore'
        data["om_points"]      # will return 'value'
    • Geng Jiawen - vote: 76

      • Justin Peel 的回答很有效,不过如果在 Python 3 中读取 json 的话,可以这样:

      • with open('data.json', encoding='utf-8') as data_file:
        data = json.loads(data_file.read())
      • 注意:使用 json.loads 代替 json.load 。在 Python 3 中,json.loads 传入字符串参数。json.load 传入类文件对象参数。 data_file.read() 返回字符串对象。

      • 实话说,我不觉得大多数情况下读取整个 json 数据会有问题。我在 JS、Java、Kotlin、cpp、rust 都试过。考虑内存问题对我来说就像个笑话 🙂

      • 换句话说,我不认为你能在不完全读取它的情况下解释 json 数据。


Why can\'t Python parse this JSON data?

  • michele asked:

    • I have this JSON in a file:
      文件里面有 json 如下:

    • {
      "maps": [
          {
              "id": "blabla",
              "iscategorical": "0"
          },
          {
              "id": "blabla",
              "iscategorical": "0"
          }
      ],
      "masks": [
          "id": "valore"
      ],
      "om_points": "value",
      "parameters": [
          "id": "valore"
      ]
      }
    • I wrote this script to print all of the JSON data:
      然后我写了脚本来打印所有 json 数据:

    • import json
      from pprint import pprint
      with open('data.json') as f:
      data = json.load(f)
      pprint(data)
    • This program raises an exception, though:
      但程序报错了:

    • Traceback (most recent call last):
      File "", line 5, in 
      data = json.load(f)
      File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
      return _default_decoder.decode(s)
      File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
      obj, end = self.raw_decode(s, idx=_w(s, 0).end())
      File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode
      obj, end = self.scan_once(s, idx)
      json.decoder.JSONDecodeError: Expecting ',' delimiter: line 13 column 13 (char 213)
    • How can I parse the JSON and extract its values?
      怎么才能解释 json,并从中取值?

  • Answers:

    • Justin Peel - vote: 2187

    • Your data is not valid JSON format. You have [] when you should have {}:
      这串数据并不是有效的 JSON 格式,有的 [] 应该是 {} :

      • [] are for JSON arrays, which are called list in Python
        [] 是 json 数组,对应 Python 的 list
      • {} are for JSON objects, which are called dict in Python
        {} 是 json 对象,对应 Python 的 dict
    • Here\'s how your JSON file should look:

      正确的 json 应该是这样的:

    • {
        "maps": [
            {
                "id": "blabla",
                "iscategorical": "0"
            },
            {
                "id": "blabla",
                "iscategorical": "0"
            }
        ],
        "masks": {
            "id": "valore"
        },
        "om_points": "value",
        "parameters": {
            "id": "valore"
        }
      }
    • Then you can use your code:
      然后是代码:

    • import json
      from pprint import pprint
      with open('data.json') as f:
        data = json.load(f)
      pprint(data)
    • With data, you can now also find values like so:
      对于这些数据,可以这样获取值:

    • data["maps"][0]["id"]
      data["masks"]["id"]
      data["om_points"]
    • Try those out and see if it starts to make sense.
      试试,看看是不是正常了。

    • Bengt - vote: 320

      • Your data.json should look like this:
        data.json 应该是这样的:

      • {
        "maps":[
             {"id":"blabla","iscategorical":"0"},
             {"id":"blabla","iscategorical":"0"}
            ],
        "masks":
             {"id":"valore"},
        "om_points":"value",
        "parameters":
             {"id":"valore"}
        }
      • Your code should be:
        代码应该是这样的:

      • import json
        from pprint import pprint
        with open('data.json') as data_file:    
        data = json.load(data_file)
        pprint(data)
      • Note that this only works in Python 2.6 and up, as it depends upon the with-statement. In Python 2.5 use from __future__ import with_statement, in Python <= 2.4, see Justin Peel\'s answer, which this answer is based upon.
        注意这只在 Python 2.6 及以上版本可用,因为它依赖于 with 。在 Python 2.5 使用 from __future__ import with_statement ,对于 Python 2.4 以下的版本,见 Justin Peel 的回答

      • You can now also access single values like this:
        这样可以获取单个值:

      • data["maps"][0]["id"]  # will return 'blabla'
        data["masks"]["id"]    # will return 'valore'
        data["om_points"]      # will return 'value'
    • Geng Jiawen - vote: 76

      • Justin Peel\'s answer is really helpful, but if you are using Python 3 reading JSON should be done like this:
        Justin Peel 的回答很有效,不过如果在 Python 3 中读取 json 的话,可以这样:

      • with open('data.json', encoding='utf-8') as data_file:
        data = json.loads(data_file.read())
      • Note: use json.loads instead of json.load. In Python 3, json.loads takes a string parameter. json.load takes a file-like object parameter. data_file.read() returns a string object.
        注意:使用 json.loads 代替 json.load 。在 Python 3 中,json.loads 传入字符串参数。json.load 传入类文件对象参数。 data_file.read() 返回字符串对象。

      • To be honest, I don\'t think it\'s a problem to load all json data into memory in most cases.I see this in JS, Java, Kotlin, cpp, rust almost every language I use.Consider memory issue like a joke to me 🙂
        实话说,我不觉得大多数情况下读取整个 json 数据会有问题。我在 JS、Java、Kotlin、cpp、rust 都试过。考虑内存问题对我来说就像个笑话 🙂

      • On the other hand, I don\'t think you can parse json without reading all of it.
        换句话说,我不认为你能在不完全读取它的情况下解释 json 数据。

版权声明:
作者:MWHLS
链接:http://panwj.top/3305.html
来源:无镣之涯
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
< <上一篇
下一篇>>