python - 如何将文本文件转换为json文件?

我有这个“.txt”文件image所以我想使用 python 将它转换为 JSON 文件 我已经尝试了很多解决方案,但由于文件的格式,它没有用。 谁能帮我,拜托! 我可以转换它以便于操作吗?

这是我的文件

Teste: 89
IGUAL
{
 "3C:67:8C:E7:F5:C8": ["b''", "-83"],
 "64:23:15:3D:25:FC": ["b'HUAWEI-B311-25FC'", "-83"],
 "98:00:6A:1D:6F:CA": ["b'WE'", "-83"],
 "64:23:15:3D:25:FF": ["b''", "-83"],
 "D4:6B:A6:C7:36:24": ["b'Wudi'", "-51"],
 "00:1E:2A:1B:A5:74": ["b'NETGEAR'", "-54"],
 "3C:67:8C:63:70:54": ["b'Vodafone_ADSL_2018'", "-33"],
 "90:F6:52:67:EA:EE": ["b'Akram'", "-80"],
 "04:C0:6F:1F:07:40": ["b'memo'", "-60"],
 "80:7D:14:5F:A7:FC": ["b'WIFI 1'", "-49"]
}

这是我试过的代码

import json
filename = 'data_strength/dbm-2021-11-21_12-11-47.963190.txt'
dict1 = {}
with open(filename) as fh:
    for line in fh:
        command, description = line.strip().split(None, 10)
        dict1[command] = description.strip()
        
out_file = open('test1.json', "w")
json.dump(dict1, out_file, indent=4, sort_key=False)
out_file.close()

最佳答案

文件中的 JSON 结构从第一次出现左大括号开始。因此,您可以这样做:

import json

INPUT = 'igual.txt'
OUTPUT = 'igual.json'

with open(INPUT) as igual:
    contents = igual.read()
    if (idx := contents.find('{')) >= 0:
        d = json.loads(contents[idx:])
        with open(OUTPUT, 'w') as jout:
            json.dump(d, jout, indent=4)

https://stackoverflow.com/questions/70287200/

相关文章:

android-jetpack-compose - Jetpack 撰写 Justified 和 R

amazon-web-services - Docker 推送错误保存凭据 : error stor

java - 当我们调用 function(2) 时,为什么这个函数返回 83 而不是 5?

spring - 摆脱 spring-boot-starter-data-mongodb 对易受攻击

rust - 在 ".map(|x| *x)"之前是否有更好的 ".collect()"替代品?

phpunit - 在 php 8.1.0 上使用 phpunit 9.4 捕获警告、通知和弃用

graphql - 为什么 graphcms graphql 给我一个 403 错误?

php - 为什么php artisan make :factory not Generating

javascript - 如何使用顺风向表格添加间距

go - 为什么 DefaultMask() 方法在 Golang 中有一个 IP 类型的接收者?