代码之家  ›  专栏  ›  技术社区  ›  Mustard Tiger

Python无法读取有效的JSON

  •  1
  • Mustard Tiger  · 技术社区  · 6 年前

    我正在从网页中提取一些HTML源代码,以提取以json格式存储的数据

    url = 'https://finance.yahoo.com/quote/SPY'
    result = requests.get(url)
    
    c = result.content
    html = BeautifulSoup(c, 'html.parser')
    scripts = html.find_all('script')
    
    sl =[]
    for s in scripts:
    
         sl.append(s)
    
    s = (sl[-3])
    s = s.contents
    s = str(s)
    s = s[119:-16]
    
    json_data = json.loads(s)
    

    运行上述命令会引发此错误:

    json.decoder.JSONDecodError: Expecting ',' delimiter: line 1 column 7506 (char7505)
    

    当我获取变量s的内容并将其传递给json格式化程序时,它被识别为正确的json。

    我使用以下网站检查json: http://jsonprettyprint.com/json-pretty-printer.php

    为什么在Python中使用json.loads()时会出现此错误?我假设它与未正确编码的字符串或转义字符的存在有关?

    4 回复  |  直到 6 年前
        1
  •  1
  •   skaul05    6 年前

    您的JSON包含某些意外标记,如 true . 使用 json.dumps

    print (json.dumps(s,indent =2))
    s = json.dumps(s)
    json_data = json.loads(s)
    
        2
  •  1
  •   ap288    6 年前
    json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 7484 (char 7483)
    

    使用失败消息,您可以打印字符串的一部分,以查看失败的位置。

    print(s[7400:7500])
    mailboxes.isPrimary=\\"true\\" AND ymreq
    

    true

        3
  •  -1
  •   Tom.chen.kang    6 年前
    import requests
    from bs4 import BeautifulSoup
    import json
    
    url = 'https://finance.yahoo.com/quote/SPY'
    result = requests.get(url)
    
    c = result.content
    html = BeautifulSoup(c, 'html.parser')
    scripts = html.find_all('script')
    
    sl =[]
    for s in scripts:
    
         sl.append(s)
    
    s = (sl[-3])
    s = s.contents
    
    a = s[0][111:-12]
    
    jjjj = json.loads(a)
    

    当你处理这个列表时,你只需要使用 str()

        4
  •  -1
  •   Lawrence Khan    6 年前

    如果它是一个有效的JSON格式的文本,那么解析器不会抱怨。这就是我测试它的方式

    //first I scraped that page
    curl https://finance.yahoo.com/quote/SPY > SPY.json
    //then tried to parse it using json
    a = open("SPY.json")
    b = json.load(a)
    ValueError: No JSON object could be decoded
    

    您可能需要首先将其解析为有效的xml。