如何将JSON字符串保存到字典?

时间:2019-03-24 20:39:54

标签: python json

我有一个脚本可以成功返回JSON字符串,但是我需要将此字符串转换为可以与JSON Server(伪造的REST API)一起使用的格式。该脚本运行良好,甚至可以将所有内容保存到文件中。我已经在JSONLint上测试了JSON,并说它是有效的。

服务器期望的格式为:

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

我的脚本当前正在返回:

{"devId": "XXXXXXXXXXXXXXXXXXXX", "dps": {"1": false, "109": false, 
"111": false, "110": false, "102": 180, "103": 0, "106": 65, "107": 0, 
"104": 65, "105": 57}}

这是我当前用于保存文件的内容:

with open("temperatures.json", "w") as write_file:
json.dump(data, write_file)

我需要添加什么到脚本中,以将JSON保存为JSON Server所需格式的文件?

2 个答案:

答案 0 :(得分:0)

您在将对象编码为JSON字符串之前先对其进行构建:

import json

data = {}
data['key'] = 'value'
json_data = json.dumps(data)

和您的对象不相同,请尝试对其进行更新。如果您提供Temperatures.json输出

答案 1 :(得分:0)

您可以获得所有这样的键:

import json

arr = '[{"a": "111", "b": "222", "c": "333", "d": "444", "e": "555"},{"a": "111", "b": "222", "c": "333", "d": "444", "e": "555"}]'
# convert string to json
j = json.loads(arr)
for idx, el in enumerate(j):
    print(el)
    for key in el:
        print(key)

您可以这样创建一个新的json:

import json
arr = '[{"a": "111", "b": "222", "c": "333", "d": "444", "e": "555"}, {"a": "111", "b": "222", "c": "333", "d": "444", "e": "555"}]'
# your final json
json_dic = {}
# convert string to json
j = json.loads(arr)
for idx, el in enumerate(j):
    print(el)
    print(el['a'])
    # create your new json
    json_dic['id'] = el['a']
    json_dic['title'] = el['b']
    json_dic['author'] = el['c']
    # json.dumps to stringify the json
    print(json.dumps(json_dic))
    for key in el:
        print(key)
相关问题