簡體   English   中英

將txt文件轉換為python中的JSON

[英]Convert txt file into JSON in python

我有一個txt文件,其格式如下所示,並且密鑰字符串不在引號中。 如何使用python轉換為JSON?

name {
  first_name: "random"
}
addresses {
  location {
    locality: "India"
    street_address: "xyz"
    postal_code: "300092"
    full_address: "street 1 , abc,India"
  }
}
projects {
  url: "www.githib.com"
}

假設您的數據為

{
    'addresses': {
        'location': {
            'full_address': 'street 1 , abc,India',
            'locality': 'India',
            'postal_code': '300092',
            'street_address': 'xyz'
        }
    },
    'name': {
        'first_name': 'random'
    },
    'projects': {
        'url': 'www.githib.com'
    }
}

使用json.dumps將dict轉換為json

In [16]: import json

In [17]: data
Out[17]:
{'addresses': {'location': {'full_address': 'street 1 , abc,India',
   'locality': 'India',
   'postal_code': '300092',
   'street_address': 'xyz'}},
 'name': {'first_name': 'random'},
 'projects': {'url': 'www.githib.com'}}

In [18]: json.dumps(data)
Out[18]: '{"name": {"first_name": "random"}, "projects": {"url": "www.githib.com"}, "addresses": {"location": {"postal_code": "300092", "full_address": "street 1 , abc,India", "street_address": "xyz", "locality": "India"}}}'

In [19]:

標准庫中沒有簡單的方法可以將數據格式轉換為JSON,因此我們需要編寫一個解析器。 但是,由於數據格式相當簡單,因此並不難。 我們可以使用標准的csv模塊讀取數據。 csv.reader將正確處理解析空格和帶引號的字符串的詳細信息。 帶引號的字符串將被視為單個標記,可以包含由單個單詞組成的標記,但不一定需要。

csv.reader通常從打開的文件中獲取其數據,但是它用途廣泛,並且還將從字符串列表中讀取其數據。 在測試時這很方便,因為我們可以將輸入數據嵌入腳本中。

我們將數據解析為嵌套字典。 跟蹤嵌套的一種簡單方法是使用堆棧,我們可以使用普通列表作為堆棧。

下面的代碼假定輸入行可以是以下三種形式之一:

  1. 普通數據。 該行由鍵-值對組成,並由至少一個空格分隔。
  2. 一個新的子對象。 該行以一個鍵開頭,並以一個大括號{結束。
  3. 當前子對象的末尾。 該行包含一個右大括號}

import csv
import json

raw = '''\
name {
  first_name: "random"
}
addresses {
  location {
    locality: "India"
    street_address: "xyz"
    postal_code: "300092"
    full_address: "street 1 , abc,India"
  }
}
projects {
  url: "www.githib.com"
}
'''.splitlines()

# A stack to hold the parsed objects
stack = [{}]

reader = csv.reader(raw, delimiter=' ', skipinitialspace=True)
for row in reader:
    #print(row)
    key = row[0]
    if key == '}':
        # The end of the current object
        stack.pop()
        continue
    val = row[-1]
    if val == '{':
        # A new subobject
        stack[-1][key] = d = {}
        stack.append(d)
    else:
        # A line of plain data
        stack[-1][key] = val

# Convert to JSON
out = json.dumps(stack[0], indent=4)
print(out)

輸出

{
    "name": {
        "first_name:": "random"
    },
    "addresses": {
        "location": {
            "locality:": "India",
            "street_address:": "xyz",
            "postal_code:": "300092",
            "full_address:": "street 1 , abc,India"
        }
    },
    "projects": {
        "url:": "www.githib.com"
    }
}

暫無
暫無

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

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