簡體   English   中英

將字符串轉換為Dict / JSON

[英]Convert string into Dict / JSON

我正在嘗試將以下數據轉換為dict,以便可以有key:value對並​​將它們嵌套:

data="Group A\n name : rey\n age : 6\n status : active\n in role : 201\n weight : 25\n interests\n Out Side : 16016\n In Side : 0\n Out : 2804\n\n name : dan\n age : 5\n status : inactive\n in role : 201\n weight : 18\n interests\n Out Side : 16016\n In Side : 0\n Out : 2804\n\n"

問題是,並非所有人都擁有:並且應該將其中一些歸為一類(即Group A一部分)。 \\n換行符絕對可以幫助我分隔它們。

這是我希望得到的結果:

[
 {
  "Group A":
   [
    {"name": "rey", "age": "6", "status": "active"},
    {"name": "dan", "age": "5", "status": "inactive"}
   ]
 }
]

我現在有什么? 我將其中一些分成dict

result = {}
for row in data.split('\n'):
  if ':' in row:
    key, value = row.split(':')
    result[key] = value.strip()

這輸出我:

{' name ': 'dan', ' weight ': '18', ' In Side ': '0', ' Out ': '2804', ' in role ': '201', ' status ': 'inactive', ' Out Side ': '16016', ' age ': '5'}但是,這與上面顯示數據的現有順序弄混了-並不是全部都出來了。

我有點是從外部程序捕獲此數據,因此僅限於Python 2.7版。 任何想法都會超級有幫助!

您應該在數據中找到模式:

  • 您的數據用空行分隔
  • 內部數據以空格開頭

使用這些觀察結果,您可以編寫:

def parse(data):
    aa = {}
    curRecord = None
    curGroup  = None

    for row in data.split('\n'):
        if row.startswith(' '): 
            # this is a new key in the inner record
            if ':' in row :
                if curRecord == None:
                    curRecord = {}
                    curGroup.append(curRecord)
                key, value = row.split(':')
                curRecord[key.strip()] = value.strip()
        elif row == '': 
            # this signal new inner record
            curRecord = None
        else: 
            # otherwise , it is a new group
            curRecord = None
            curGroup = []
            aa[row.strip()] = curGroup
    return aa

>>> import json
>>> print( json.dumps(parse(data)) );    
{"Group A": [{"name": "rey", ... }, {"name": "dan", ... }]}

我將使用setdefault在您的setdefault中創建新列表。 如果您有B,C,D組,這將適用於多個組。

import json

def convert_string(data):
    result = {}
    current = ""
    key_no = -1
    for pair in data.split("\n"):
        if ':' not in pair:
            if "Group" in pair:
                result.setdefault(pair,[])
                current = pair
                key_no = -1
        elif "name" in pair:
            result[current].append({})
            key_no +=1
            key, value = pair.split(':')
            result[current][key_no][key.strip()] = value.strip()
        elif all(s not in pair.lower() for s in ("weight","in role","out","in side")):
            key, value = pair.split(':')
            result[current][key_no][key.strip()] = value.strip()
    return result

print (json.dumps(convert_string(d),indent=4))

{
    "Group A": [
        {
            "name": "rey",
            "age": "6",
            "status": "active"
        },
        {
            "name": "dan",
            "age": "5",
            "status": "inactive"
        }
    ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM