无法弄清楚如何防止数组中的最后一个键没有逗号。由于它被导出到.Json文件,因此最后一个键不应该有“,”。
我知道你可以使用.Last();
来检测它,但我似乎无法做到这一点。有什么建议吗?
//Data Path
string dataPath = @"..\..\FileIOExtraFiles\DataFieldsLayout.txt";
string[] dataList = File.ReadAllLines(dataPath);
//save Data data
using (StreamWriter outStream = new StreamWriter(outputFolder + @"\CharacterStringData3.json"))
{
outStream.WriteLine("{");
for (int i = 0; i < dataFile.Length; i++)
{
string s = dataFile[i];
char last = s.Last();
if (s == "")
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
}
else
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\",");
}
}
outStream.WriteLine("}");
}
输出:
{
"data1":"item1",
"data2":item2",
"lastKey":item3",//trying to remove comma from last key in array.
}
答案 0 :(得分:3)
正如其他人所指出的那样,手动构建json是没有意义的,但考虑到这是一个更多关于技术的问题,这里有一种方法:你可以改成它:
Video
后缀将用于除最后一次之外的每次迭代。
答案 1 :(得分:1)
更改此
library(dplyr)
result <- DT %>%
group_by(town,tc) %>%
mutate_each(funs(mean,sd,
uplimit = (mean(.) + 1.96*sd(.)),
lowlimit = (mean(.) - 1.96*sd(.)),
Aoutlier = as.integer(. >= mean(.) - 1.96*sd(.) &
. <= mean(.) - 1.96*sd(.))),
-town,-tc)
到此
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
答案 2 :(得分:0)
不是在每一步使用outStream.WriteLine()
,而是将其存储在字符串中。然后,您可以从该字符串中删除最后一个逗号并立即写入整个字符串:
//Get last index of comma
int lastCommaIndex = outputString.LastIndexOf(',');
//Create new StringBuilder with everything before the last comma
StringBuilder sb = new StringBuilder(outputString.Substring(0,lastCommaIndex));
//Add everything after the last comma, or just add a closing brace
//sb.Append("}"); //This instead of next line
sb.Append(outputString.Substring(lastCommaIndex+1));
//Add contents of StringBuilder to the Stream
outSteam.WriteLine(sb);