使用python在json中拆分字符串

2024-06-17 13:21:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的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文件。在python下面的两个字段中,max和min是不同的。在

^{pr2}$

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


Tags: 文件jsonobjecttitletyperequiredfirstnamemin
3条回答

您的JSON文件似乎写错了(示例)。这不是一个列表。它只是一个关联的数组(或Python中的dictionary)。另外,您似乎没有正确使用json.dumps。它只需要一个参数。我还认为只需内联创建字典会更容易。你似乎没有正确地划分最小值和最大值。在

以下是正确的输入:

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

这是你的新代码:

^{pr2}$

Table+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')

结果:

^{pr2}$

你可以这样做:

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"值保持不变。在

相关问题 更多 >