如何读取普通的txt文件并使用python转换为json?

时间:2016-01-11 04:00:12

标签: python json csv

我目前的代码:

try:
    recipients = { 'HBRj6x6huUKyWtuv643DRrrCbkd2kDj2Z6': 50.0
                 , 'HNGY9f6Hh6uiVYcoGUnW3xCRVToBP9LujR': 50.0
                 , 'HPcWvavNTR1qywMzq1figttGddHnMGHGWx': 50.0
                 , 'H88DbndzTeN66Q9RyVeiPsDYWwevJph3Lx': 50.0
                 , 'HG818gFwAVfNGZKT8F9qv9aj2du7QZEuMP': 50.0
                 , 'HFY7mMZuUcohP3bgLAnQrLxuWxDqcXEydW': 50.0
                 , 'HBrvtTteTARdehFYWYmok4HaQp3TvFiGGw': 50.0
                 , 'HMT7agiynUhR656GTaRUsHndSEFQVR2n2D': 50.0
                 , 'HNrvbV9aqRnJ6ZJ1e9sY9CDsJFqoTFaFch': 50.0
                 , 'HQBiwms9cVrcVFJ2fKVbhab666JePeRTnz': 50.0
                 }
    bitcoind.sendmany("", recipients)

我试图从包含如下列表的普通txt文件中读取recipients JSON

HBRj6x6huUKyWtuv643DRrrCbkd2kDj2Z6
HNGY9f6Hh6uiVYcoGUnW3xCRVToBP9LujR
HPcWvavNTR1qywMzq1figttGddHnMGHGWx
H88DbndzTeN66Q9RyVeiPsDYWwevJph3Lx
HG818gFwAVfNGZKT8F9qv9aj2du7QZEuMP
HFY7mMZuUcohP3bgLAnQrLxuWxDqcXEydW
HBrvtTteTARdehFYWYmok4HaQp3TvFiGGw
HMT7agiynUhR656GTaRUsHndSEFQVR2n2D
HNrvbV9aqRnJ6ZJ1e9sY9CDsJFqoTFaFch
HQBiwms9cVrcVFJ2fKVbhab666JePeRTnz

如何以编程方式将普通txt转换为JSON(添加({ ' : and 50.0 etc)?我已尝试过这样做:

with open('data.json') as data_file:    
    data = json.load(data_file)

try:
    recipients = (data)

错误:

Traceback (most recent call last):
  File "C:\Users\X\Desktop\sendmany.py", line 11, in <module>
    data = json.load(data_file)
  File "C:\Python27\lib\json\__init__.py", line 290, in load
    **kw)
  File "C:\Python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 3 (char 2)

2 个答案:

答案 0 :(得分:1)

def get_value(hash_value)
    """Function to return approriate value."""
    return 50

receipt_dict = {}
with open("data.json", "r") as plain_text:
    for line in plain_text:
        hash_value = line.strip()
        receipt_dict[hash_value] = get_value(hash_value)

json_string = json.dumps(receipt_dict)

try:
     bitcoind.sendmany("", json_string)
...

答案 1 :(得分:0)

这是直截了当的,通过从文件行构建数据结构(例如字典),然后使用json.dumps()将其转换为JSON:

import json

requests = {}
with open('data.json') as infile:  # though that data really isn't in JSON format
    for line in infile:
        requests[line.strip()] = 50


# now to JSON stuff with `answer`

print(json.dumps(answer))