【问题标题】:ValueError: Expected object or value - reading open Recipes dataValueError:预期的对象或值 - 读取打开的食谱数据
【发布时间】:2020-06-14 22:03:42
【问题描述】:

我正在尝试读取 Json 文件。代码已成功选择文件但未成功读取数据,并且 recipes = pd.read_json(data_json) 显示错误 ValueError: Expected object or value。我正在使用以下代码

with open('recipeitems-latest.json', 'r',encoding ="utf8") as f:
     data = (line.strip() for line in f)
     data_json = format(','.join(data))
recipes = pd.read_json(data_json)

这是我要读取的 json 数据:

[{
    "_id": {
        "$oid": "5160756b96cc62079cc2db15"
    },
    "name": "Drop Biscuits and Sausage Gravy",
    "ingredients": "Biscuits\n3 cups All-purpose Flour\n2 Tablespoons Baking Powder\n1/2 teaspoon Salt\n1-1/2 stick (3/4 Cup) Cold Butter, Cut Into Pieces\n1-1/4 cup Butermilk\n SAUSAGE GRAVY\n1 pound Breakfast Sausage, Hot Or Mild\n1/3 cup All-purpose Flour\n4 cups Whole Milk\n1/2 teaspoon Seasoned Salt\n2 teaspoons Black Pepper, More To Taste",
    "url": "assasasasa",
    "image": "saassasasa",
    "ts": {
        "$date": 1365276011104
    },
    "cookTime": "PT30M",
    "source": "thepioneerwoman",
    "recipeYield": "12",
    "datePublished": "2013-03-11",
    "prepTime": "PT10M",
    "description": "Late Saturday afternoon, after Marlboro Man had returned home with the soccer-playing girls, and I had returned home with the..."
}, {
    "_id": {
        "$oid": "5160756d96cc62079cc2db16"
    },
    "name": "Hot Roast Beef Sandwiches",
    "ingredients": "12 whole Dinner Rolls Or Small Sandwich Buns (I Used Whole Wheat)\n1 pound Thinly Shaved Roast Beef Or Ham (or Both!)\n1 pound Cheese (Provolone, Swiss, Mozzarella, Even Cheez Whiz!)\n1/4 cup Mayonnaise\n3 Tablespoons Grated Onion (or 1 Tbsp Dried Onion Flakes))\n1 Tablespoon Poppy Seeds\n1 Tablespoon Spicy Mustard\n1 Tablespoon Horseradish Mayo Or Straight Prepared Horseradish\n Dash Of Worcestershire\n Optional Dressing Ingredients: Sriracha, Hot Sauce, Dried Onion Flakes Instead Of Fresh, Garlic Powder, Pepper, Etc.)",
    "url": "sasasasasa",
    "image": "sasasasasa",
    "ts": {
        "$date": 1365276013902
    },
    "cookTime": "PT20M",
    "source": "thepioneerwoman",
    "recipeYield": "12",
    "datePublished": "2013-03-13",
    "prepTime": "PT20M",
    "description": "When I was growing up, I participated in my Episcopal church's youth group, and I have lots of memories of weekly meetings wh..."
}, {
    "_id": {
        "$oid": "5160756f96cc6207a37ff777"
    },
    "name": "Morrocan Carrot and Chickpea Salad",
    "ingredients": "Dressing:\n1 tablespoon cumin seeds\n1/3 cup / 80 ml extra virgin olive oil\n2 tablespoons fresh lemon juice\n1 tablespoon honey\n1/2 teaspoon fine sea salt, plus more to taste\n1/8 teaspoon cayenne pepper\n10 ounces carrots, shredded on a box grater or sliced whisper thin on a mandolin\n2 cups cooked chickpeas (or one 15- ounce can, drained and rinsed)\n2/3 cup / 100 g  dried pluots, plums, or dates cut into chickpea-sized pieces\n1/3 cup / 30 g fresh mint, torn\nFor serving: lots of toasted almond slices, dried or fresh rose petals - all optional (but great additions!)",
    "url": "sasasasasa",
    "image": "sasasasasa",
    "ts": {
        "$date": 1365276015332
    },
    "datePublished": "2013-01-07",
    "source": "101cookbooks",
    "prepTime": "PT15M",
    "description": "A beauty of a carrot salad - tricked out with chickpeas, chunks of dried pluots, sliced almonds, and a toasted cumin dressing. Thank you Diane Morgan."
}, {
    "_id": {
        "$oid": "5160757096cc62079cc2db17"
    },
    "name": "Mixed Berry Shortcake",
    "ingredients": "Biscuits\n3 cups All-purpose Flour\n2 Tablespoons Baking Powder\n3 Tablespoons Sugar\n1/2 teaspoon Salt\n1-1/2 stick (3/4 Cup) Cold Butter, Cut Into Pieces\n1-1/4 cup Buttermilk\n1/2 teaspoon Almond Extract (optional)\n Berries\n2 pints Mixed Berries And/or Sliced Strawberries\n1/3 cup Sugar\n Zest And Juice Of 1 Small Orange\n SWEET YOGURT CREAM\n1 package (7 Ounces) Plain Greek Yogurt\n1 cup Cold Heavy Cream\n1/2 cup Sugar\n2 Tablespoons Brown Sugar",
    "url": "assasasasaas",
    "image": "asasasasasa",
    "ts": {
        "$date": 1365276016700
    },
    "cookTime": "PT15M",
    "source": "thepioneerwoman",
    "recipeYield": "8",
    "datePublished": "2013-03-18",
    "prepTime": "PT15M",
    "description": "It's Monday! It's a brand new week! The birds are chirping! The coffee's brewing! Everything has such hope and promise!     A..."
}, {
    "_id": {
        "$oid": "5160757496cc6207a37ff778"
    },
    "name": "Pomegranate Yogurt Bowl",
    "ingredients": "For each bowl: \na big dollop of Greek yogurt\n2 tablespoons fresh pomegranate juice\na drizzle of honey\na handful of puffed quinoa crisps (or other cereal/granola)\nsprinkling of toasted sunflower seeds\noptional: whole pomegranate seeds or fresh/dried rose petals, a bit of bee pollen",
    "url": "http://www.101cookbooks.com/archives/pomegranate-yogurt-bowl-recipe.html",
    "image": "http://www.101cookbooks.com/mt-static/images/food/breakfast_yogurt_bowl.jpg",
    "ts": {
        "$date": 1365276020318
    },
    "datePublished": "2013-01-20",
    "source": "101cookbooks",
    "recipeYield": "Serves 1.",
    "prepTime": "PT5M",
    "description": "A simple breakfast bowl made with Greek yogurt, fresh pomegranate juice, puffed quinoa cereal, toasted sunflower seeds, and honey."
}, {
    "_id": {
        "$oid": "5160757596cc62079cc2db18"
    },
    "name": "Krispy Easter Eggs",
    "ingredients": "4 Tablespoons Butter\n1 package (10 Ounces) Mini Marshmallows\n6 cups Rice Krispies\n Assorted Sprinkles\n Small Chocolate Easter Eggs\n Plastic Easter Eggs",
    "url": "http://thepioneerwoman.com/cooking/2013/03/krispy-easter-eggs/",
    "image": "http://static.thepioneerwoman.com/cooking/files/2013/03/DSC_9637.jpg",
    "ts": {
        "$date": 1365276021992
    },
    "cookTime": "PT5M",
    "source": "thepioneerwoman",
    "recipeYield": "12",
    "datePublished": "2013-03-25",
    "prepTime": "PT20M",
    "description": "Imagine the Easter Bunny laying an egg.     Wait. That’s not anatomically possible.     And anyway, the Easter Bunny is a b..."
}]

这是错误回溯:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Users\Ata.Malik\PycharmProjects\First_Project\venv\lib\site-packages\pandas\util\_decorators.py", line 214, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\Ata.Malik\PycharmProjects\First_Project\venv\lib\site-packages\pandas\io\json\_json.py", line 608, in read_json
    result = json_reader.read()
  File "C:\Users\Ata.Malik\PycharmProjects\First_Project\venv\lib\site-packages\pandas\io\json\_json.py", line 731, in read
    obj = self._get_object_parser(self.data)
  File "C:\Users\Ata.Malik\PycharmProjects\First_Project\venv\lib\site-packages\pandas\io\json\_json.py", line 753, in _get_object_parser
    obj = FrameParser(json, **kwargs).parse()
  File "C:\Users\Ata.Malik\PycharmProjects\First_Project\venv\lib\site-packages\pandas\io\json\_json.py", line 857, in parse
    self._parse_no_numpy()
  File "C:\Users\Ata.Malik\PycharmProjects\First_Project\venv\lib\site-packages\pandas\io\json\_json.py", line 1089, in _parse_no_numpy
    loads(json, precise_float=self.precise_float), dtype=None
ValueError: Expected object or value

任何帮助将不胜感激。因为我不知道我做错了什么。

【问题讨论】:

    标签: python json python-3.x pandas


    【解决方案1】:
    recipes = pd.read_json('recipeitems-latest.json')
    

    应该工作

    【讨论】:

    • 不幸的是无法正常工作 - 仍然出现错误:ValueError: Expected object or value
    • @AtaUrRahmanMalik 忘记其他代码行。你不需要open json 填充。熊猫会处理这一切。所以只使用这一行。跨度>
    • 这正是我所做的。尝试只执行一行,不幸的是得到了同样的错误。
    • 我什至已经验证了jsonlint.com 上的 json 格式……它是有效的。仍然报同样的错误
    • @AtaUrRahmanMalik 我的机器上没有错误。你用的是哪个版本的熊猫?
    【解决方案2】:

    您也可以在这里使用json_normalize

    with open('recipeitems-latest.json', 'r+') as f:
        data = json.load(f)
    
    df = pd.json_normalize(data)
    print(df)
    

    输出:

                                     name                                        ingredients  ...                  _id.$oid       ts.$date
    0     Drop Biscuits and Sausage Gravy  Biscuits\n3 cups All-purpose Flour\n2 Tablespo...  ...  5160756b96cc62079cc2db15  1365276011104
    1           Hot Roast Beef Sandwiches  12 whole Dinner Rolls Or Small Sandwich Buns (...  ...  5160756d96cc62079cc2db16  1365276013902
    2  Morrocan Carrot and Chickpea Salad  Dressing:\n1 tablespoon cumin seeds\n1/3 cup /...  ...  5160756f96cc6207a37ff777  1365276015332
    3               Mixed Berry Shortcake  Biscuits\n3 cups All-purpose Flour\n2 Tablespo...  ...  5160757096cc62079cc2db17  1365276016700
    4             Pomegranate Yogurt Bowl  For each bowl: \na big dollop of Greek yogurt\...  ...  5160757496cc6207a37ff778  1365276020318
    5                  Krispy Easter Eggs  4 Tablespoons Butter\n1 package (10 Ounces) Mi...  ...  5160757596cc62079cc2db18  1365276021992
    

    【讨论】:

    • 谢谢@NYC Coder .. 它给了我另一个错误不幸的是.. json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
    • 当我使用 open 和 .read() 方法读取文件并打印它时.. 它打印以下字符串:[{ "_id": { "$oid": "5160756b96cc62079cc2db15 " }, "name": "Drop Biscuits and Sausage Gravy", "ingredients": "Biscuits\n3 杯通用面粉\n2 汤匙烘焙.....加上文件的其余部分......你认为加载错误可能是由于字符串开头的?
    • 是的,JSON 必须以 [ 或 { 开头。在此之前不应有其他角色。
    • 我已经跳过了前几个字符以 [ ... 现在它在第二条记录上给了我错误 .. 错误是:json.decoder.JSONDecodeError: Extra data: line 18第 2 列 (char 925) 第 18 行包含 },第 19 行包含下一条记录。有什么想法吗?
    • 现在可能还有其他角色。你能验证你的 JSON 吗?您的代码也适用于您在上面发布的 JSON 吗?
    猜你喜欢
    • 2021-09-26
    • 2017-11-01
    • 2020-12-28
    • 2022-11-30
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多