无法读取json

问题描述 投票:0回答:1
ValueError                                Traceback (most recent call last)
<ipython-input-8-7c5fcf8552e0> in <cell line: 1>()
----> 1 df2 = pd.read_json('/content/drive/MyDrive/Hackathon project/PS 1,2/no_pii_action_history.json')

6 frames
/usr/local/lib/python3.10/dist-packages/pandas/io/json/_json.py in _parse_no_numpy(self)
   1319         if orient == "columns":
   1320             self.obj = DataFrame(
-> 1321                 loads(json, precise_float=self.precise_float), dtype=None
   1322             )
   1323         elif orient == "split":

ValueError: Unexpected character found when decoding 'NaN'

我们尝试了2种方法

1)

df2 = pd.read_json('/content/drive/MyDrive/Hackathon project/PS 1,2/no_pii_action_history.json')
import json

def handle_nan(value):
    if value == "nan":  # replace "nan" with the appropriate representation of NaN in your data
        return float('nan')
    return value

# Specify the file path
file_path = '/content/drive/MyDrive/Hackathon project/PS 1,2/no_pii_action_history.json'

# Open the file and load JSON data with custom handling
with open(file_path, 'r') as file:
    data = json.load(file, object_hook=handle_nan)

这两种方法都不起作用

python json nan unexpected-token
1个回答
0
投票

您可以使用 None 或其他哨兵值来表示 NaN 试试这个:

import json

def handle_nan(value):
    if value == "nan":
        return None  
    return value

file_path = '/content/drive/MyDrive/Hackathon project/PS 1,2/no_pii_action_history.json'

with open(file_path, 'r') as file:
    data = json.load(file, object_hook=handle_nan)
© www.soinside.com 2019 - 2024. All rights reserved.