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

删除 HTML 标签并将 JSON 数组解析为键/值对象

删除 HTML 标签并将 JSON 数组解析为键/值对象

炎炎设计 2023-10-31 15:22:59
我正在使用 JSON 数组有效负载,我想将其提取到一个单独的对象中以进行下游处理。有效负载是动态的,并且可以在 JSON 数组中具有多个嵌套级别,但第一级始终有一个id作为唯一标识符的字段。[{'field1': [],  'field2': {'field2_1': string,   'field2_2': 'string',   'field2_3': 'string'},  'field3': '<html> strings <html>'},  'id':1}{'field1': [],  'field2': {'field2_1': string,   'field2_2': 'string',   'field2_3': 'string'},  'field3': '<html> strings <html>'},  'id':2}{'field1': [],  'field2': {'field2_1': string,   'field2_2': 'string',   'field2_3': 'string'},  'field3': '<html> strings <html>'},  'id':3},{'field1': [],  'field2': {'field2_1': string,   'field2_2': 'string',   'field2_3': 'string'},  'field3': '<html> strings <html>'},  'id':4}]有效负载在更多字段或具有不同类型数据的更多嵌套字段方面不限于此结构。但该id字段将始终附加到有效负载中的每个对象。我想创建一个字典(对数据类型的其他建议开放),其中该id字段和该对象中的其他所有内容都作为清理后的字符串,没有任何括号或 HTML 标签等。输出应该是这样的(取决于数据类型):{1: string string string strings,2: string string string strings,3: string string string strings,4: string string string strings}这是一个非常通用的例子。我在使用所有嵌套和内容导航 JSON 数组时遇到问题,只想以id干净的方式提取内容和其余内容。任何帮助表示赞赏!
查看完整描述

1 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

您可以使用它beautifulsoup来清理所有标签中的字符串。例如:


from bs4 import BeautifulSoup



lst = [{'field1': [],

  'field2': {'field2_1': 'string1',

   'field2_2': 'string2',

   'field2_3': 'string3'},

  'field3': '<html> strings4 <html>',

  'id':1},

{'field1': [],

  'field2': {'field2_1': 'string1',

   'field2_2': 'string2',

   'field2_3': 'string3'},

  'field3': '<html> strings4 <html>',

  'id':2},

{'field1': [],

  'field2': {'field2_1': 'string1',

   'field2_2': 'string2',

   'field2_3': 'string3'},

  'field3': '<html> strings4 <html>',

  'id':3},

{'field1': [],

  'field2': {'field2_1': 'string1',

   'field2_2': 'string2',

   'field2_3': 'string3'},

  'field3': '<html> strings4 <html>',

  'id':4}]


def flatten(d):

    if isinstance(d, dict):

        for v in d.values():

            yield from flatten(v)

    elif isinstance(d, list):

        for v in d:

            yield from flatten(v)

    elif isinstance(d, str):

        yield d


out = {}

for d in lst:

    out[d['id']] = ' '.join(map(str.strip, BeautifulSoup(' '.join(flatten(d)), 'html.parser').find_all(text=True)))


print(out)

印刷:


{1: 'string1 string2 string3 strings4', 2: 'string1 string2 string3 strings4', 3: 'string1 string2 string3 strings4', 4: 'string1 string2 string3 strings4'}



查看完整回答
反对 回复 2023-10-31
  • 1 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信