【问题标题】:In Python how do I write characters such as ½ or ¼ to json file在 Python 中,如何将 ½ 或 ¼ 等字符写入 json 文件
【发布时间】:2020-09-03 15:21:36
【问题描述】:

块引用

在这里查看类似的问题,我认为我已经解决了这个问题,而且相当简单。我正在尝试写这样一行:

“1/4 公斤牛肉”

到一个 json 文件。我正在从一个字符串(行)数组中写入。

lines 是由一个带有回车的长字符串(成分)构建的。

ingredients = "__Name: 0: Cottage pie\n__scrape_schema\n__url:https://www.bbcgoodfood.com/recipes/cottage-pie\n3 tbsp olive oil\n1 ¼kg beef mince\n2 onions,finely chopped\n3 carrots,chopped\n"

lines=ingredients.split('\n')

我看到建议是这样做:

import json
data={}
with open('test.json', 'w', encoding="utf-8") as json_file: 
    for line in lines:
        json.dump(line, json_file)

我没有收到错误消息,但在 json 文件中我收到以下注释:

SyntaxError: JSON.parse: JSON 数据的第 1 行第 25 列的 JSON 数据后出现意外的非空白字符

而写入的数据是:

"\u00bckg 牛肉"

这是显示两者的 json 文件的顶部:

SyntaxError: JSON.parse: JSON 数据第 1 行第 25 列的 JSON 数据后出现意外的非空白字符 "__Name: 0: Cottage pie""__scrape_schema ""__url: https://www.bbcgoodfood.com/recipes/cottage-pie""3 tbsp 橄榄油""1 \u00bckg 牛肉碎""2 个洋葱,鳍...

我不是要本地化,我真的只需要处理字符分数。所以我不确定我还应该做什么?

【问题讨论】:

  • 什么是lines - 为什么要逐行写入文件?
  • lines 是一个字符串数组。我已经更新了我的问题。
  • 请分享lines或其中的一部分
  • 从哪里得到 SyntaxError?
  • @jz_ 一行一行地写一个json文件是没有意义的。您只需with open('test.json', 'w') as f: json.dump(lines, f)

标签: python json


【解决方案1】:

似乎是这样的:

with open('test.json', 'w') as f: json.dump(lines, f)

解决问题。 for 循环似乎引入了第二个不再存在的问题。

【讨论】:

    猜你喜欢
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 2014-10-03
    • 2022-12-05
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    相关资源
    最近更新 更多