为了账号安全,请及时绑定邮箱和手机立即绑定

两个json对象之间的逗号

两个json对象之间的逗号

长风秋雁 2021-09-11 16:46:50
我正在从伪 xml 格式文件创建一个 json 文件。但是我在 json 对象之间得到逗号,这是我不想要的。这是我得到的样本:[{"a": a , "b": b } , {"a": a , "b": b }]但是我想要这个:{"a": a , "b": b } {"a": a , "b": b }它可能不是有效的 json,但我想要这样,以便我可以通过执行以下操作来对其进行洗牌:shuf -n 100000 original.json > sample.json否则,它将只是一大行 json这是我的代码:def read_html_file(file_name):    f = open(file_name,"r", encoding="ISO-8859-1")    html = f.read()    parsed_html = BeautifulSoup(html, "html.parser")    return parsed_htmldef process_reviews(parsed_html):    reviews = []    for r in parsed_html.findAll('review'):        review_text = r.find('review_text').text        asin = r.find('asin').text        rating = r.find('rating').text        product_type = r.find('product_type').text        reviewer_location = r.find('reviewer_location').text        reviews.append({            'review_text': review_text.strip(),            'asin': asin.strip(),            'rating': rating.strip(),            'product_type': product_type.strip(),            'reviewer_location': reviewer_location.strip()        })    return reviewsdef write_json_file(file_name, reviews):    with open('{f}.json'.format(f=file_name), 'w') as outfile:        json.dump(reviews, outfile)if __name__ == '__main__':    parser = optparse.OptionParser()    parser.add_option('-f', '--file_name',action="store", dest="file_name",    help="name of the input html file to parse", default="positive.html")    options, args = parser.parse_args()    file_name = options.file_name    html = read_html_file(file_name)    reviews_list = process_reviews(html)    write_json_file(file_name,reviews_list)第一个 [ ] 是因为reviews = [], 我可以手动删除它,但我也不希望我的 json 对象之间有逗号。
查看完整描述

2 回答

?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

您要的不是 JSON。根据定义,标准规定对象之间必须有逗号。您有两种选择可以继续:

  1. 更新您的解析器以符合标准(强烈推荐)。

  2. 出于显示目的或您可能有的其他内部处理目的,如果您真的想要您指定的结构:捕获 JSON 对象并将其转换为其他内容,但请不要将其称为 JSON,因为它不是。


查看完整回答
反对 回复 2021-09-11
?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

您在问题中混合了一些概念!

1.你有什么不是dict,而是list的dicts。

2. 你的输入元素list和预期的输出都没有 JSON


现在寻求解决方案,如果您想简单地print将对象comma分开而不将它们分开,那么您只需要print列出所有元素,您可以做什么:


sample = [{"a": "a" , "b": "b" } , {"a": "a" , "b": "b" }]

print(" ".join([str(element) for element in sample]))

现在,如果您真正想要的是将其作为 JSON 对象进行操作,您有两种选择,使用jsonlib:


将您的每个元素添加sample为 Json 并单独操作

它们已经格式化为 Json,因此您可以使用jsonlib操作它们以将( dumps)漂亮地打印为字符串或任何其他操作:


import json    

for element in sample:

        print(json.dumps(element, indent = 4))

使您的示例列表成为 Json

您可以将所有元素添加到单个key,让我们说添加到一个key被调用的elements,会是什么:


sample_json = {"elements": []}

for data in sample:

    sample_json["elements"].append(data)

# Output from sample_json

# {'elements': [{'a': 'a', 'b': 'b'}, {'a': 'a', 'b': 'b'}]}

或者您可以将每个元素添加到不同的key. 例如,我将创建一个计数器,并且计数器的每个数字将key为该特定定义一个不同的数字element:


sample_json = {}

counter = 0

for data in sample:

    sample_json[counter] = data

    counter += 1

# Output from sample_json

# {0: {'a': 'a', 'b': 'b'}, 1: {'a': 'a', 'b': 'b'}}

keys对于第二种情况,您也可以使用文本。


查看完整回答
反对 回复 2021-09-11
  • 2 回答
  • 0 关注
  • 310 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号