在python中将以下数据转换为JSON格式

2024-07-05 07:28:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由其他程序生成的包含以下内容的文件。请注意,每一行的末尾都有一个新行字符。你知道吗

{'a':1,'b':534}
{'a':4,'b':882}
{'a':2,'b':964}
.
.
so on...

如何将其转换为有效的JSON格式?你知道吗

上面应该印成这样

{
    "Sale": [
        {
            "a": 1,
            "b": 534
        },
        {
            "a": 4,
            "b": 882
        },
        {
            "a": 2,
            "b": 964
        }
    ]
}

我可以在JQuery中完成,但是我需要在python中完成,因为我不擅长python,但是我需要通过bash脚本使它可以运行,因此需要将它转换为python脚本。你知道吗

我将分享jquery解决方案,以防您需要参考。你知道吗

result = replaceAll(result,"'","\"");
result = replaceAll(result,"}, {",",");
result = replaceAll(result,"}{","},{"); 
result = replaceAll(result,"}\n{","},{");
result = "{\"Sale\":["+result+"]}";
//alert(result);

replaceAll函数为

function replaceAll(str, find, replace) {
 var i = str.indexOf(find);
 if (i > -1){
   str = str.replace(find, replace); 
   i = i + replace.length;
   var st2 = str.substring(i);
   if(st2.indexOf(find) > -1){
     str = str.substring(0,i) + replaceAll(st2, find, replace);
   }       
 }
 return str;
}

上面的工作,但我需要一个python的替代品。你知道吗


Tags: 文件程序脚本ifvarresultsalesubstring
2条回答
from ast import literal_eval
import json
sale = []
with open(filepath) as f:
    lines = f.read()
    for line in lines:
       sale.append(literal_eval(line))
json.dumps({"sale":sale}, indent=4)
from ast import literal_eval
with open('data.txt') as f:
    sale = [literal_eval(line) for line in f]
    data = {'Sale': sale}
    print(data)

输出

{'Sale': [{'a': 1, 'b': 534}, {'a': 4, 'b': 882}, {'a': 2, 'b': 964}]}

在那里,您可以使用^{} library将此文件写入JSON格式的文件。你知道吗

import json
json.dumps(data, indent=4)

相关问题 更多 >