Python - 将.txt内容转换为json格式

时间:2017-06-05 06:35:17

标签: python json

Name: Donald J. Trump
Username: @realDonaldTrump
Post: I look forward to paying my respects to our brave men and women on this Memorial Day at Arlington National Cemetery later this morning.
post's link: https://twitter.com/realDonaldTrump/status/869170615881793536
Replies: 16,259 replies
Retweet: 15,103 retweets
Likes: 90,839 likes
Date: 5:36 AM - 29 May 2017

大家好,以上是我的first.txt文件中每个数据块的格式。我想阅读它并将其更改为如下所示的json格式,并将其存储到second.txt文件中。

def convert_to_json(path, name, username, post, link, replies, retweets, likes, retweetby, date, domainname):
with open(path, 'a') as file:
    stringData = [{"ContentUrl": link,
    "Text": post,
    "PublishDate": date.strip(),
    "Title": "",
    "SourceUrl": domainname,
    "SocialNetwork": media,
    "Source": "",
    "Author": name,
    "Like_count": likes.strip(),
    "Replies_count": replies.strip(),
    "Retweets_count": retweets.strip(),
    "Schema": "SOCIAL_MEDIA"}]

    objData = json.load(stringData)
    file.write(stringData)

上面的代码假设接收数据然后将其附加到second.txt文件。但是,我的代码无法将我想要的数据附加到我的second.txt文件中。控制台没有显示明显的错误,我在这里寻求所有专家的建议和帮助。

3 个答案:

答案 0 :(得分:0)

您没有正确使用json.load;试试这样:

record = {"ContentUrl": link,
    "Text": post,
    "PublishDate": date.strip(),
    "Title": "",
    "SourceUrl": domainname,
    "SocialNetwork": media,
    "Source": "",
    "Author": name,
    "Like_count": likes.strip(),
    "Replies_count": replies.strip(),
    "Retweets_count": retweets.strip(),
    "Schema": "SOCIAL_MEDIA"}  

with open(path, 'a') as file:
    objData = json.load(file)
    objData.append(record)
    file.write(json.dumps(objData))

答案 1 :(得分:0)

  1. 尝试json.dumps而不是加载
  2. 为什么要在列表中包装dict?
  3. 写入文件json.dumps的结果,而不是对象

    with open(path, 'a+') as file:
        stringData = {"ContentUrl": link,
        "Text": post,
        "PublishDate": date.strip(),
        "Title": "",
        "SourceUrl": domainname,
        "SocialNetwork": media,
        "Source": "",
        "Author": name,
        "Like_count": likes.strip(),
        "Replies_count": replies.strip(),
        "Retweets_count": retweets.strip(),
        "Schema": "SOCIAL_MEDIA"}
    
        objData = json.dumps(stringData)
        file.write(objData)
    

答案 2 :(得分:0)

将所有数据添加到列表(stringData),最后使用

stringData写入第二个文件
stringData = [] #init

def addToDataToBeWritten(path, name, username, post, link, replies, retweets, likes, retweetby, date, domainname):    

    row = {"ContentUrl": link,
    "Text": post,
    "PublishDate": date.strip(),
    "Title": "",
    "SourceUrl": domainname,
    "SocialNetwork": media,
    "Source": "",
    "Author": name,
    "Like_count": likes.strip(),
    "Replies_count": replies.strip(),
    "Retweets_count": retweets.strip(),
    "Schema": "SOCIAL_MEDIA"}
    stringData.append(raw)

''' Read and call the method here'''
with open(path, 'w') as file:  
    file.write(json.dumps(stringData))