【问题标题】:How can i manipulate json values我如何操作 json 值
【发布时间】:2018-07-18 04:23:16
【问题描述】:

我有一个rest api,它返回数据库查询的json&json看起来像

{"keys": "[{'aht': Decimal('238'), 'month': 'April '}, {'aht': Decimal('201'), 'month': 'August '}, {'aht': Decimal('236'), 'month': 'December '}, {'aht': Decimal('230'), 'month': 'February '}, {'aht': Decimal('228'), 'month': 'January '}, {'aht': Decimal('202'), 'month': 'July '}, {'aht': Decimal('201'), 'month': 'June '}, {'aht': Decimal('239'), 'month': 'March '}, {'aht': Decimal('214'), 'month': 'May '}, {'aht': Decimal('235'), 'month': 'November '}, {'aht': Decimal('221'), 'month': 'October '}, {'aht': Decimal('147'), 'month': 'September'}]", "success": true}

所以从下面

{'aht': Decimal('238'), 'month': 'April '}

删除小数()

预期:

{'aht': '238', 'month': 'April '}

我可以在 python 3.6 或 js 中处理它。

【问题讨论】:

  • 您需要在发送之前处理它,否则您不会发送 JSON - 因此您唯一的选择是您使用的任何服务器端语言 - 您还需要更改所有 '" 获取有效的 JSON .. 不过,目前你实际上有 JSON,这会导致对象 {keys: "[{... this is just string value for keys...}]"} - 所以从技术上讲,你的服务器正在创建一些甚至不接近 JSON 的东西

标签: javascript python json python-3.x


【解决方案1】:

您可以尝试在应用程序中使用 JSON 字符串之前对其进行预处理,如下所示。

或者,如果您希望 REST API 发送此输出以与其他内容一起使用,而唯一的问题是 JS/Python(当您想将其作为 JSON 处理时),请为您的 REST 端点实现一个参数以指定是否清理(JSON 格式)是否必要。根据该参数,在服务器端进行必要的处理以删除 Decimal 等。

let str = `{"keys": "[{'aht': Decimal('2'), 'month': 'April '}, {'aht': Decimal('20'), 'month': 'August '}, {'aht': Decimal('236'), 'month': 'December '}, {'aht': Decimal('230'), 'month': 'February '}, {'aht': Decimal('228'), 'month': 'January '}, {'aht': Decimal('202'), 'month': 'July '}, {'aht': Decimal('201'), 'month': 'June '}, {'aht': Decimal('239'), 'month': 'March '}, {'aht': Decimal('214'), 'month': 'May '}, {'aht': Decimal('235'), 'month': 'November '}, {'aht': Decimal('221'), 'month': 'October '}, {'aht': Decimal('147'), 'month': 'September'}]", "success": true}`;

let cleanJSON = str.replace(/Decimal\('([0-9]*)'\)/g, function(x) {
  return x.substring(9, x.length - 2);
});

console.log(JSON.parse(cleanJSON));

【讨论】:

    【解决方案2】:

    正如@Jaromanda 所说,您的 API 数据不是您想要的格式。请再次检查。如果你得到我在这里提到的数据,你可以使用我的方法。

    var jsonData = {"keys": [{'aht': "Decimal('238')", 'month': 'April '}, {'aht': "Decimal('201')", 'month': 'August '}, {'aht': "Decimal('236')", 'month': 'December '}, {'aht': "Decimal('230')", 'month': 'February '}, {'aht': "Decimal('228')", 'month': 'January '}, {'aht': "Decimal('202')", 'month': 'July '}, {'aht': "Decimal('201')", 'month': 'June '}, {'aht': "Decimal('239')", 'month': 'March '}, {'aht': "Decimal('214')", 'month': 'May '}, {'aht': "Decimal('235')", 'month': 'November '}, {'aht': "Decimal('221')", 'month': 'October '}, {'aht': "Decimal('147')", 'month': 'September'}], "success": true}
    
    if( jsonData.keys ) {
    
      jsonData.keys.map( ( data ) => {
      
        if( data.aht && data.aht.match( /Decimal\(/ ) ) {
        
          data.aht = data.aht.replace( "Decimal('", "" );
          data.aht = data.aht.replace( "')", "" );
        
        }
      
      } )
      
    
    }
    
    console.log(jsonData.keys)

    【讨论】:

    • 数据按照问题中的要求出现,可能是因为它是使用数学运算进行嵌套查询的结果。我看到您在此处用作输入的引号有所不同。
    【解决方案3】:

    将其转换为 dict 的字符串表示形式,然后使用 ast.literal_eval 制作它的实际 dict 会更容易(比使用普通 Python eval 更安全)。您必须执行以下步骤:

    1. 仅将所有 Decimal('111') 字符串替换为 '111'。
    2. 将“真”和“假”替换为“真”和“假”
    3. 使用ast.literal_eval 评估整体字典
    4. 使用第二次调用ast.literal_eval 来评估“keys”字典值

    看起来像这样:

    import re
    import ast
    
    def make_dict(s):
        # extract integer part of Decimal values
        ss = re.sub(r"Decimal\('(\d+)'\)", r"\1", s)
    
        # convert boolean literals
        ss = ss.replace("true", "True")
        ss = ss.replace("false", "False")
    
        # convert dict
        dictval = ast.literal_eval(ss)
    
        # convert 'keys' entry
        dictval['keys'] = ast.literal_eval(dictval['keys'])
    
        return dictval
    

    它在行动:

    text = """{"keys": "[{'aht': Decimal('238'), 'month': 'April '}, {'aht': Decimal('201'), 'month': 'August '}, {'aht': Decimal('236'), 'month': 'December '}, {'aht': Decimal('230'), 'month': 'February '}, {'aht': Decimal('228'), 'month': 'January '}, {'aht': Decimal('202'), 'month': 'July '}, {'aht': Decimal('201'), 'month': 'June '}, {'aht': Decimal('239'), 'month': 'March '}, {'aht': Decimal('214'), 'month': 'May '}, {'aht': Decimal('235'), 'month': 'November '}, {'aht': Decimal('221'), 'month': 'October '}, {'aht': Decimal('147'), 'month': 'September'}]", "success": true}"""
    
    import pprint
    pprint.pprint(make_dict(text))
    

    给予:

    {'keys': [{'aht': 238, 'month': 'April '},
              {'aht': 201, 'month': 'August '},
              {'aht': 236, 'month': 'December '},
              {'aht': 230, 'month': 'February '},
              {'aht': 228, 'month': 'January '},
              {'aht': 202, 'month': 'July '},
              {'aht': 201, 'month': 'June '},
              {'aht': 239, 'month': 'March '},
              {'aht': 214, 'month': 'May '},
              {'aht': 235, 'month': 'November '},
              {'aht': 221, 'month': 'October '},
              {'aht': 147, 'month': 'September'}],
     'success': True}
    

    请使用str 将字典转换为字符串来告诉人们停止在您的数据库中存储字典。

    【讨论】:

      【解决方案4】:

      正如每个人所说,您能做的最好的事情就是告诉中间件人来完成这项工作,因为这对前端来说是不必要的负担。否则,您可以使用正则表达式 (JavaScript) 替换 Decimal() 和 '。

      var jsonObj = {"keys": "[{'aht': Decimal('238'), 'month': 'April '}, {'aht': Decimal('201'), 'month': 'August '}, {'aht': Decimal('236'), 'month': 'December '}, {'aht': Decimal('230'), 'month': 'February '}, {'aht': Decimal('228'), 'month': 'January '}, {'aht': Decimal('202'), 'month': 'July '}, {'aht': Decimal('201'), 'month': 'June '}, {'aht': Decimal('239'), 'month': 'March '}, {'aht': Decimal('214'), 'month': 'May '}, {'aht': Decimal('235'), 'month': 'November '}, {'aht': Decimal('221'), 'month': 'October '}, {'aht': Decimal('147'), 'month': 'September'}]", "success": true}
      
      // cleans the JSON object to generate a valid JSON.
      jsonObj.keys = jsonObj.keys.replace(/Decimal[\(^0-9]|\)/g, '').replace(/'/gm, '"');
      jsonObj.keys = JSON.parse(jsonObj.keys);
      
      console.log(jsonObj);

      【讨论】:

        【解决方案5】:

        您可以像下面这样简单地使用字符串replace() 和正则表达式:

        var keysObj = {"keys": "[{'aht': Decimal('238'), 'month': 'April '}, {'aht': Decimal('201'), 'month': 'August '}, {'aht': Decimal('236'), 'month': 'December '}, {'aht': Decimal('230'), 'month': 'February '}, {'aht': Decimal('228'), 'month': 'January '}, {'aht': Decimal('202'), 'month': 'July '}, {'aht': Decimal('201'), 'month': 'June '}, {'aht': Decimal('239'), 'month': 'March '}, {'aht': Decimal('214'), 'month': 'May '}, {'aht': Decimal('235'), 'month': 'November '}, {'aht': Decimal('221'), 'month': 'October '}, {'aht': Decimal('147'), 'month': 'September'}]", "success": true};
        
        keysObj.keys = keysObj.keys.replace(/Decimal[\(^0-9]|\)/g, '');
        console.log(keysObj);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-21
          • 1970-01-01
          • 1970-01-01
          • 2016-06-09
          • 2013-06-19
          相关资源
          最近更新 更多