【问题标题】:Splitting a string in json using python使用python在json中拆分字符串
【发布时间】:2018-05-11 01:09:45
【问题描述】:

我有一个简单的 Json 文件

输入.json

[
{
    "title": "Person",
    "type": "object",
    "required": "firstName",
    "min_max": "200/600"
},
{
    "title": "Person1",
    "type": "object2",
    "required": "firstName1",
    "min_max": "230/630"
},
{
    "title": "Person2",
    "type": "object2",
    "required": "firstName2",
    "min_max": "201/601"
},
{
    "title": "Person3",
    "type": "object3",
    "required": "firstName3",
    "min_max": "2000/6000"
},
{
    "title": "Person4",
    "type": "object4",
    "required": "firstName4",
    "min_max": "null"
},
{
    "title": "Person4",
    "type": "object4",
    "required": "firstName4",
    "min_max": "1024 / 256"
},

{
    "title": "Person4",
    "type": "object4",
    "required": "firstName4",
    "min_max": "0"
}

]

我正在尝试使用新数据创建一个新的 json 文件。我想将“min_max”分成两个不同的字段,即最小值和最大值。下面是用python编写的代码。

import json
input=open('input.json', 'r')
output=open('test.json', 'w')
json_decode=json.load(input)

result = []
for item in json_decode:
    my_dict={}
    my_dict['title']=item.get('title')
    my_dict['min']=item.get('min_max')
    my_dict['max']=item.get('min_max')
    result.append(my_dict)

data=json.dumps(result, output)
output.write(data)
output.close()

如何将字符串拆分为两个不同的值。另外,有没有可能按顺序打印json输出。

【问题讨论】:

    标签: python json string python-2.7 dictionary


    【解决方案1】:

    您的 JSON 文件似乎写错了(示例一)。它不是一个列表。它只是一个关联的数组(或 Python 中的字典)。此外,您似乎没有正确使用json.dumps。它只需要 1 个参数。我还认为只创建内联字典会更容易。而且您似乎没有正确拆分 min_max。

    这是正确的输入:

    [{
        "title": "Person",
        "type": "object",
        "required": "firstName",
        "min_max": "20/60"
    }]
    

    这是你的新代码:

    import json
    
    with open('input.json', 'r') as inp, open('test.json', 'w') as outp:
        json_decode=json.load(inp)    
        result = []
        for temp in json_decode:
            minMax = temp["min_max"].split("/")
            result.append({
                "title":temp["title"],
                "min":minMax[0],
                "max":minMax[1]
            })    
        data=json.dumps(result)
        outp.write(data)
    

    【讨论】:

    • 谢谢@neil。它显示“IndexError:列表索引超出范围”。我相信这是因为我的 json 文件太大了。我该如何克服呢?
    • @neil - 我刚刚在我的问题中编辑了 json 数据。它只是数据的一个实例。我有越来越多类似的数据。
    • 你必须在每一个之间加逗号。不看数据不知道怎么看。
    • @neil - 你指的是什么逗号?另外,我没有任何具体数据。想象一下同样的数据有越来越多的字典。谢谢。
    • 在我看来,您的 min_max 值中没有 /,这会导致它在尝试引用 @987654326 中的值时遇到问题@ 来自.split('/') 调用的数组。在尝试将其添加到结果之前,您需要检查以确保 len(minMax) == 2 - 如果不是,请添加在这种情况下执行您想要执行的操作的代码。
    【解决方案2】:

    表格 + Python == 熊猫

    import pandas as pd
    
    # Read old json to a dataframe
    df = pd.read_json("input.json")
    
    # Create two new columns based on min_max
    # Removes empty spaces with strip()
    # Returns [None,None] if length of split is not equal to 2
    df['min'], df['max'] = (zip(*df['min_max'].apply
                            (lambda x: [i.strip() for i in x.split("/")] 
                             if len(x.split("/"))== 2 else [None,None])))
    
    # 'delete' (drop) min_max column
    df.drop('min_max', axis=1, inplace=True)
    
    # output to json again
    df.to_json("test.json",orient='records')
    

    结果:

    [{'max': '600',
     'min': '200',
      'required': 'firstName',
      'title': 'Person',
      'type': 'object'},
     {'max': '630',
      'min': '230',
      'required': 'firstName1',
      'title': 'Person1',
      'type': 'object2'},
     {'max': '601',
      'min': '201',
      'required': 'firstName2',
      'title': 'Person2',
      'type': 'object2'},
     {'max': '6000',
      'min': '2000',
      'required': 'firstName3',
      'title': 'Person3',
      'type': 'object3'},
     {'max': None,
      'min': None,
     ...
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      import json 
      
      nl=[]
      for di in json.loads(js):
          min_,sep,max_=map(lambda s: s.strip(), di['min_max'].partition('/'))
          if sep=='/':
              del di['min_max']
              di['min']=min_
              di['max']=max_
          nl.append(di)
      
      print json.dumps(nl)    
      

      这会使不能分成两个值的"min_max" 值保持不变。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-20
        • 1970-01-01
        • 1970-01-01
        • 2010-09-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多