从JSON格式提取特定数据并转换为二项式

时间:2018-10-22 03:27:10

标签: python

我有此JSON格式文件

{'Sensory and Communication': {'Sensory and Communication': {'Visual Impairment': 'Yes', 'Hearing Impairment': 'No', 'Communication': 'No

,我希望提取所有“是/否”并将其分别替换为1/0。

这是我当前的代码

import json
with open('C:\\Users\Desktop\\IFA.txt') as f:
json_data = json.load(f)

if  json_data['Sensory and Communication']['Visual Impairment']=='Yes':
   ['Sensory and Communication']['Visual Impairment'] == '1'

我想要一个IF / ELSE语句,以便它能够读取是YES还是No并将其替换为二项式格式

4 个答案:

答案 0 :(得分:0)

尝试一下:

json_data=dict(json_data)
for k,v in json_data['Sensory and Communication']['Sensory and Communication'].items():
   if v.lower()=='yes':
      json_data['Sensory and Communication']['Sensory and Communication'][k]=1
   else:
      json_data['Sensory and Communication']['Sensory and Communication'][k]=0

然后现在:

print(json_data)

是:

{'Sensory and Communication': {'Sensory and Communication': {'Visual Impairment': 1, 'Hearing Impairment': 0, 'Communication': 0}}}

要使用二项式格式,请使用布尔值:

json_data=dict(json_data)
for k,v in json_data['Sensory and Communication']['Sensory and Communication'].items():
   if v.lower()=='yes':
      json_data['Sensory and Communication']['Sensory and Communication'][k]=True
   else:
      json_data['Sensory and Communication']['Sensory and Communication'][k]=False

然后现在:

print(json_data)

是:

{'Sensory and Communication': {'Sensory and Communication': {'Visual Impairment': True, 'Hearing Impairment': False, 'Communication': False}}}

答案 1 :(得分:0)

代码的最后一行是错误的。而不是'==',您应该使用'='。 “ ==”等于具有布尔输出的运算。您还可以使用转储功能保存新字典。

if json_data['Sensory and Communication']['Sensory and Communication']['Visual Impairment'] == 'Yes':
    json_data['Sensory and Communication']['Sensory and Communication']['Visual Impairment'] = '1'
    fp = open('C:\\Workspace\\input_new.json','w');
    json.dump(json_data,fp,indent=1)

答案 2 :(得分:0)

又甜又甜:)

在所需位置循环遍历所有val。假设根据您的文件,它们将为是和否-我们将它们替换为二进制布尔值。

LOCATOR = 'Sensory and Communication'

for k,v in json_data[LOCATOR][LOCATOR].iteritems():
    json_data[LOCATOR][LOCATOR][k] = '1' if v == 'Yes' else '0'

答案 3 :(得分:0)

递归算法将为您做到这一点:

def replace_yes_no(data_dict):
    for key, val in data_dict.items():
        if isinstance(val, dict):
            replace_yes_no(val)
        elif isinstance(val, str):
            if val == 'Yes':
                data_dict[key] = 1
            elif val == 'No':
                data_dict[key] = 0
问题中给出的输入的

输出:

{'Sensory and Communication': {'Sensory and Communication': {'Visual Impairment': 1, 'Hearing Impairment': 0, 'Communication': 0}}}