添加“;”在JSON对象中的每个循环之后

时间:2019-12-15 21:33:20

标签: python json

我正在尝试使用json添加一个;在每个json对象循环之后。基本上,我有一个循环的列表,然后将其添加为“转换”为json:

i = 1
for _ in range(3):

    data = {}

    data['country'] = 'SE'
    data['profileNickname'] = 'TEST {}'.format(i)
    i += 1

with open("random.json", "w") as writeJSON:
    writeJSON.write(json.dumps(data, indent=2))

但是结果却只是一个普通的json:

{
  "country": "SE",
  "profileNickname": "TEST 1",
},
{
  "country": "SE",
  "profileNickname": "TEST 2",
}

我的问题和我想做的是,我想在每个循环后添加;,以便使输出看起来像这样:

{
  "country": "SE",
  "profileNickname": "TEST 1",
};{
  "country": "SE",
  "profileNickname": "TEST 2",
}

我知道会将其标记为无效json,但这是我的目标,我的目标是能够添加;除最后一个循环外,每个循环之后。

1 个答案:

答案 0 :(得分:1)

不确定为什么需要它,但这不是问题:)

import json

items = []
for i in range(1, 4):
    items.append({
        'country': 'SE',
        'profileNickname': 'TEST {}'.format(i)
    })

with open("random.json", "w") as writeJSON:
    buffer = ""
    for i, item in enumerate(items):
        buffer += json.dumps(item, indent=2)

        if i != len(items) - 1:
            buffer += ';'

    writeJSON.write(buffer)

写入文件

{
  "country": "SE",
  "profileNickname": "TEST 1"
};{
  "country": "SE",
  "profileNickname": "TEST 2"
};{
  "country": "SE",
  "profileNickname": "TEST 3"
}

另一个不使用缓冲区字符串的示例

import json

items = []
for i in range(1, 4):
    items.append({
        'country': 'SE',
        'profileNickname': 'TEST {}'.format(i)
    })

with open("random.json", "w") as writeJSON:
    for i, item in enumerate(items):
        writeJSON.write(json.dumps(item, indent=2))

        if i != len(items) - 1:
            writeJSON.write(';')