使用python在json中拆分字符串

时间:2017-11-27 17:50:43

标签: python json string python-2.7 dictionary

我有一个简单的Json文件

input.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"进入两个不同的领域,即。,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输出。

1 个答案:

答案 0 :(得分:0)

表+ Python == Pandas

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,
 ...