我收到一个以类似方式构建的JSON文件:
{"Value1" : "1", "Value2" : "2", "Value3" : "3"},
{"Value4" : "4", "Value5" : "5", "Value5" : "5"}
不幸的是,我无法控制如何解析此JSON。因此,我需要删除引号,因此整数不会被视为字符串,因此:
{"Value1" : 1, "Value2" : 2, "Value3" : 3},
{"Value4" : 4, "Value5" : 5, "Value5" : 5}
我觉得这可以用正则表达式来实现(虽然它可能有点“脏”),但我不知道如何去做。有什么建议? 编辑:所有值都是JSON文件中的整数。
答案 0 :(得分:2)
我完全正确地做事,但是使用json解析JSON文件,转换和往返而不明确知道它的结构听起来像一团糟。所以,这是你所追求的快速和肮脏的正则表达式解决方案:
import re
with open("data.json") as inp:
lines = inp.readlines()
with open("clean.json", "w") as output:
for line in lines:
output.write(re.sub(r'"(\d+)"', r"\1", line))
答案 1 :(得分:1)
解决方案代码:
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
//declare variables
int n = 0;
int counter = 0;
double score = 0.0;
double total = 0.0;
double avg = 0.0;
double scoreTotal = 0.0;
double totalTotal = 0.0;
//Prompt user for number of assignments
cout << "How many assignments are there? ";
cin >> n;
counter = 0;
do
{
counter++;
//prompt user for score */count up for each query*/
cout << "What is the score for assignment number " << counter << "? ";
cin >> score;
//prompt user for totals */count up for each total*/
cout << "What is the total score available for assignment number " << counter << "? ";
cin >> total;
}
while(counter < n);
//calculate averages
scoreTotal += score;
totalTotal += total;
avg = ((scoreTotal / totalTotal) * 100) / n;
//output how much it was out of and percent
cout << "Your total is " << scoreTotal << " out of " << totalTotal << ", or " << avg << "%" << endl;
return 0;
}
答案 2 :(得分:0)
如何使用import json
with open("input-file.json") as json_input_file:
for line in json_input_file:
# remove end of line comma (avoid removing in last line)
if line.endswith(','):
line = line[:-1]
# parse values to ints
line_json = {k: int(v) for k, v in json.loads(line).items()}
# do something with json
print line_json
模块加载每一行?
import json
with open("input-file.json") as json_input_file:
with open("result-file.json", 'w+') as json_file_result:
for line in json_input_file:
# remove end of line comma (avoid removing in last line)
if line.endswith(','):
line = line[:-1]
# parse values to ints
line_json = {k: int(v) for k, v in json.loads(line).items()}
# do something with json
json_file_result.write(json.dumps(json_line) + "\n")
如果要编写结果文件:
result-file.json
这将生成文件{"Value3": 3, "Value2": 2, "Value1": 1}
{"Value5": 5, "Value4": 4}
:
{{1}}