簡體   English   中英

如何將字符串轉換為有效的 json 或 yaml

[英]How to convert string to valid json or yaml

我有一個大型腳本,它使用 dataframe 條目解析 js,但為了縮短問題,我將我需要的內容放在一個單獨的變量中。 我的變量包含以下值

value = "{from:[3,4],to:[7,4],color:2},{from:[3,6],to:[10,6],color:3}"

我應用以下腳本並獲取這樣的數據

value = "{from:[3,4],to:[7,4],color:2},{from:[3,6],to:[10,6],color:3}"

def parse_json(value):
    arr = value.split("},")
    arr = [x+"}" for x in arr]
    arr[-1] = arr[-1][:-1]
    
    return json.dumps({str(i):add_quotation_marks(x) for i, x in enumerate(arr)})

def add_quotation_marks(value):
    words = re.findall(r'(\w+:)', value)
    for word in words:
        value = value.replace(word[:-1], f'"{word[:-1]}"')
    return json.loads(value)

print(parse_json(value))
{"0": {"from": [3, 4], "to": [7, 4], "color": 2}, "1": {"from": [3, 6], "to": [10, 6], "color": 3}}

腳本正確執行,但我需要得到稍微不同的結果。 這就是我想要得到的結果:

{
  "0": {
    "from": {
      "0": "3",
      "1": "4"
    },
    "to": {
      "0": "7",
      "1": "4"
    },
    "color": "2"
  },
  "1": {
    "from": {
      "0": "3",
      "1": "6"
    },
    "to": {
      "0": "10",
      "1": "6"
    },
    "color": "3"
  }
}

這是有效的 json 和有效的 yaml。請告訴我該怎么做

在這種情況下,我建議使用正則表達式方法:

res = []

# iterates over each "{from:...,to:...,color:...}" group separately
for obj in re.findall(r'\{([^}]+)}', value):
    item = {}

    # iterates over each "...:..." key-value separately
    for k, v in re.findall(r'(\w+):(\[[^]]+]|\d+)', obj):
        if v.startswith('['):
            v = v.strip('[]').split(',')

        item[k] = v

    res.append(item)

這會在res中產生這個 output :

[{'from': ['3', '4'], 'to': ['7', '4'], 'color': '2'}, {'from': ['3', '6'], 'to': ['10', '6'], 'color': '3'}]

由於您的值可以包含逗號,因此嘗試在逗號或其他標記上拆分是相當棘手的,而使用這些正則表達式來匹配您想要的值反而更穩定。

下面是將value轉換為所需的 output 的代碼。

import json5  # pip install json5

value = "{from:[3,4],to:[7,4],color:2},{from:[3,6],to:[10,6],color:3}"

def convert(str_value):
    str_value = f"[{str_value}]"  # added [] to make it a valid json
    parsed_value = json5.loads(str_value)  # convert to python object
    output = {}  # create empty dict

    # Loop through the list of dicts. For each item, create a new dict
    # with the index as the key and the value as the value. If the value
    # is a list, convert it to a dict with the index as the key and the
    # value as the value. If the value is not a list, just add it to the dict.
    for i, d in enumerate(parsed_value):
        output[i] = {}
        for k, v in d.items():
            output[i][k] = {j: v[j] for j in range(len(v))} if isinstance(v, list) else v

    return output

print(json5.dumps(convert(value)))

Output

{
  "0": {     
    "from": {
      "1": 4
    },
    "to": {
      "0": 7,
      "1": 4
    },
    "color": 2
  },
  "1": {
    "from": {
      "0": 3,
      "1": 6
    },
    "to": {
      "0": 10,
      "1": 6
    },
    "color": 3
  }
}
  • json5 package 允許您將 javascrip object 轉換為 python 字典,因此您不必執行split("},{")
  • 然后添加[]使字符串成為有效的 json。
  • 然后使用json5.loads()加載字符串
  • 現在您可以遍歷字典並將其轉換為所需的 output 格式。

暫無
暫無

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

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