Python 将所有非字符串JSON值转换为字符串值
在python中,我使用JSON,其中所有值都必须更改为字符串。这些值可以是数字、布尔值、null或任何值Python 将所有非字符串JSON值转换为字符串值,python,json,Python,Json,在python中,我使用JSON,其中所有值都必须更改为字符串。这些值可以是数字、布尔值、null或任何值 { "obj1": [ { "n1": "n", "n2": 1, "n3": true }, { "n1": "n", "n2": 1, "n3": null } ] } 预期结果是所有值都应格式化为字符串 例如: { "obj1": [ { "n1"
{
"obj1": [
{
"n1": "n",
"n2": 1,
"n3": true
},
{
"n1": "n",
"n2": 1,
"n3": null
}
]
}
预期结果是所有值都应格式化为字符串
例如:
{
"obj1": [
{
"n1": "n",
"n2": "1",
"n3": "true"
},
{
"n1": "n",
"n2": "1",
"n3": "null"
}
]
}
谢谢你 我这里有一个答案给你。下面的脚本将以您指定的格式获取一个JSON对象,对其进行迭代并创建一个新的JSON对象,其中非字符串值将转换为带有
JSON.dumps
的字符串
这个脚本接受一个JSON对象——如果您是从一个字符串开始的——那么您将需要使用JSON.loads(myString)将其转换为一个对象代码>
导入json;
myJSONObj={“obj1”:[{“n1”:“n”,“n2”:1,“n3”:True},{“n1”:“n”,“n2”:1,“n3”:None}]};
newJSON={};
对于myJSONObj中的obj:
newJSON[obj]=[];
对于myJSONObj[obj]中的项目:
newJSONArrayObj={};
对于键,项中的值。项()
如果不是isinstance(值,str):
newJSONArrayObj[key]=json.dumps(值);
其他:
newJSONArrayObj[key]=值;
newJSON[obj].append(newJSONArrayObj);
newJSONString=json.dumps(newJSON);
打印(newJSONString);
下面是带有注释的相同代码:
import json;
# assigning the source json object
myJSONObj = {"obj1": [{"n1": "n", "n2": 1, "n3": True}, {"n1": "n", "n2": 1, "n3": None}]};
# creating a new target json object, empty
newJSON = {};
# enter the obj1 object
for obj in myJSONObj:
# create the key from the existing obj1 object, and assign an empty array
newJSON[obj] = [];
# loop through all the array items in the source obj1 array
for item in myJSONObj[obj]:
# for each, create a new empty json object
newJSONArrayObj = {};
# for each of the key-value pairs in the object in the array
for key, value in item.items():
# in case that the value is not a string, dump it to the new object as a string with its original key
if not isinstance(value, str):
newJSONArrayObj[key] = json.dumps(value);
# otherwise, just assign the string to the key in the new object
else:
newJSONArrayObj[key] = value;
# finally push the new object into the array
newJSON[obj].append(newJSONArrayObj);
# converting the new JSON object to a string and printing it
newJSONString = json.dumps(newJSON);
print(newJSONString);
让我知道这是否对您有效。为什么不迭代您的对象和str()
值?我在这里添加了一个答案,请让我知道这是否解决了您的问题?否则,请添加一些信息,我会看看我是否能提供帮助。是的,这非常有帮助,谢谢!