Estoy usando python 3.6 e intento descargar el archivo json (350 MB) como marco de datos de pandas usando el código a continuación. Sin embargo, me sale el siguiente error:
data_json_str = "[" + ",".join(data) + "] "TypeError: sequence item 0: expected str instance, bytes found
¿Cómo puedo corregir el error?
import pandas as pd # read the entire file into a python array with open('C:/Users/Alberto/nutrients.json', 'rb') as f: data = f.readlines() # remove the trailing "\n" from each line data = map(lambda x: x.rstrip(), data) # each element of 'data' is an individual JSON object. # i want to convert it into an *array* of JSON objects # which, in and of itself, is one large JSON object # basically... add square brackets to the beginning # and end, and have all the individual business JSON objects # separated by a comma data_json_str = "[" + ",".join(data) + "]" # now, load it into pandas data_df = pd.read_json(data_json_str)Según su código, parece que está cargando un archivo JSON que tiene datos JSON en cada línea separada. read_json admite un argumento de lines para datos como este:
data_df = pd.read_json('C:/Users/Alberto/nutrients.json', lines=True)Nota
Quitelines=Truesi tiene un solo objeto JSON en lugar de objetos JSON individuales en cada línea.
Usando el módulo json, puede analizar el json en un objeto python, luego crear un marco de datos a partir de eso:
import json import pandas as pd with open('C:/Users/Alberto/nutrients.json', 'r') as f: data = json.load(f) df = pd.DataFrame(data)Si abre el archivo como binario ( 'rb' ), obtendrá bytes. Qué tal si:
with open('C:/Users/Alberto/nutrients.json', 'rU') as f:Además, como se indica en esta respuesta, también puede usar pandas directamente como:
df = pd.read_json('C:/Users/Alberto/nutrients.json', lines=True)