将所有非字符串JSON值转换为字符串值

时间:2019-03-19 21:19:49

标签: python json

在python中,我有JSON,其中所有值都必须更改为字符串。这些值可以是数字,布尔值,null或其他任何值。

{
  "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"
    }
  ]
}

谢谢!!!

1 个答案:

答案 0 :(得分:1)

在这里我为您解答。下面的脚本将采用您指定的格式的JSON对象,对其进行迭代,并创建一个新的json对象,其中非字符串值将通过json.dumps转换为字符串。

此脚本采用JSON对象-如果您以字符串开头-那么您将需要使用json.loads(myString);将其转换为对象

import json;

myJSONObj = {"obj1": [{"n1": "n", "n2": 1, "n3": True}, {"n1": "n", "n2": 1, "n3": None}]};

newJSON = {};

for obj in myJSONObj:
    newJSON[obj] = [];
    for item in myJSONObj[obj]:
        newJSONArrayObj = {};
        for key, value in item.items():
            if not isinstance(value, str):
                newJSONArrayObj[key] = json.dumps(value);
            else:
                newJSONArrayObj[key] = value;
        newJSON[obj].append(newJSONArrayObj);

newJSONString = json.dumps(newJSON);
print(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);

让我知道这是否对您有用。