10

I have some JSON data but all the keys are in UPPER case. How to parse them and convert the keys to lower? I am using jQuery.

for example:

JSON data:

{"ID":1234, "CONTENT":"HELLO"}

Desired output:

{id:1234, content:"HELLO"}
SwiftMango
  • 15,092
  • 13
  • 71
  • 136

7 Answers7

16

How about this:

json.replace(/"([^"]+)":/g, 
    function($0, $1) { return ('"' + $1.toLowerCase() + '":'); }
);

The regex captures the key name $1 and converts it to lower case.

Live demo: http://jsfiddle.net/bHz7x/1/

[edit] To address @FabrícioMatté's comment, another demo that only matches word characters: http://jsfiddle.net/bHz7x/4/

zcoop98
  • 2,590
  • 1
  • 18
  • 31
Christophe
  • 27,383
  • 28
  • 97
  • 140
  • 2
    May not work very well if you have escaped `"` inside the property name - rare use case but just noting. ([fiddle](http://jsfiddle.net/bHz7x/3/)) – Fabrício Matté Feb 04 '13 at 23:20
  • 1
    @FabrícioMatté that's an excellent point, in the case of keys that contain special characters we'd need to clarify what "convert to lower case" means. Maybe [\w] would make more sense than [^"] – Christophe Feb 04 '13 at 23:29
  • 1
    A space after the property name will break it. Ex: {"ID" :1234, "CONTENT":"HELLO"}'; ID wont be lowercased because of the space before the colon. – Raikol Amaro Feb 06 '20 at 20:15
  • 1
    json.replace(/"([^"]+)"\s*:/g,function($0,$1){return ('"'+$1.toLowerCase()+'":');})); This takes care of the spaces – Raikol Amaro Feb 06 '20 at 20:42
5

Iterate over the properties and create lowercase properties while deleting old upper case ones:

var str = '{"ID":1234, "CONTENT":"HELLO"}';

var obj = $.parseJSON(str);
$.each(obj, function(i, v) {
    obj[i.toLowerCase()] = v;
    delete obj[i];
});

console.log(obj);
//{id: 1234, content: "HELLO"} 

Fiddle

Or you can just build a new object from the old one's properties:

var obj = $.parseJSON(str),
    lowerCased = {};
$.each(obj, function(i, v) {
    lowerCased[i.toLowerCase()] = v;
});

Fiddle

References:

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
  • in case if any key is lowercase already, it will delete key i think – zb' Feb 04 '13 at 23:25
  • @eicto correct. From OP's question: "all the keys are in UPPER case" so I believe that wouldn't happen. If there might be lowercase keys, the second solution may be used but that will overwrite some existing properties nevertheless. – Fabrício Matté Feb 04 '13 at 23:26
  • @eicto The statement in OP's question makes this an impossibility. And no matter how you perform the conversion, if you use regex you will end up with 2 keys with the same name. When parsing the string into an object, this would return a much worse parse error in Strict mode or just overwrite the existing property as well in non-strict mode. – Fabrício Matté Feb 04 '13 at 23:28
  • I believe (case insensitively) duplicated keys are out of the scope of this question. These would require a special handling that'd most likely break the code which requires the original object's properties lowercased. – Fabrício Matté Feb 04 '13 at 23:34
1

That is function:

function JSON_Lower_keys(J) {
   var ret={};
   $.map(JSON.parse(J),function(value,key){
             ret[key.toLowerCase()]=value;
   })
   return ret;
}

that is call:

console.log(JSON_Lower_keys('{"ID":1234, "CONTENT":"HELLO"}'))
zb'
  • 8,071
  • 4
  • 41
  • 68
  • `$.map` is supposed to make a return array with the returned values inside the callback, the generic iterative function `$.each` would make more sense if you're not building an array with `$.map`, just saying. – Fabrício Matté Feb 04 '13 at 23:24
0

You can stick with js and use Objeck.keys()

var oldObj = { "ID":123, "CONTENT":"HI" }
var keysUpper = Object.keys(oldObj)
var newObj = {}
for(var i in keysUpper){
   newObj[keysUpper[i].toLowerCase()] = oldObj[keysUpper[i]]
}
console.log(JSON.stringify(newObj))

Copy and paste into your browser console (F12) >> output: {"id":123,"content":"HI"}

Gabe
  • 5,997
  • 5
  • 46
  • 92
0

I'm not good at explaining an idea But the library "jsonpath" of the following link https://github.com/dchester/jsonpath/ allows to manipulate, and filter any json data or array converted to json using regular expressions or JSONPath addresses.

Example 1: to display a category contained in the json variable using the address of the value to obtain:

jsonpath.query(json, '$["Bienestar"][2]');

this is the same as if I use json["Bienestar"][2]; without library.

Example 2: to display all categories using a jsonpath regular expression:

jsonpath.nodes(json, '$..[?(@)]');

Example 3: convert all existing values ​​within each category to uppercase of the json variable:

jsonpath.apply(json, '$..curso', function(value){return value.toUpperCase()});

for any text in Lower Case change "toUpperCase()" to "toLowerCase()"

Example 4: example of the above explained, but with jquery ajax

/* library: https://github.com/dchester/jsonpath */
(function($){
  var json;
  var arg='balnero';
  var url='https://cedfer2.github.io/ex/c.json';
  $.ajax({
    type: 'GET',
    url: url,
    dataType: 'text',
    error: function() {
      console.log('{error!}');
    },
    beforeSend: function() {
      console.log('{cargando...(show spinner)}');
    },
    complete: function() {
      console.log('{peticionCompleta...(hide spinner)}');
    },
    success: function (data, textStatus, jqXHR) {
      console.log('success:');
      json=$.parseJSON(data);
      console.log('-------[success data: string find in json with valor in varable arg]-------');
      console.log('arg valor:' + arg);
      console.log(
        jsonpath.query(json, '$..[?(@.curso.toUpperCase().indexOf("'+arg.toUpperCase()+'")>=0)]')
        );
      console.log('-------[success data: convert string find in json uppercase with valor in varable arg]-------');
      console.log(jsonpath.apply(json, '$..[?(@.toUpperCase().indexOf("'+arg.toUpperCase()+'")>=0)]', function(value) { return value.toUpperCase() }));
      console.log('--[show new structure json in the category "Bienestar" item 2: without library js]--');
      console.log(json["Bienestar"][2]);
    }
  });
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cedfer2.github.io/ex/jsonpath.min.js"></script>
ced
  • 1
  • 1
  • Answers which are just a dump of code with not explanation are rarely upvoted, especially on 7 year old questions which are already adequately answered. Also, this appears to do the opposite of what the OP wanted; namely, change the keys from upper to lower case. This answer changes the values to upper case... – Heretic Monkey Oct 12 '20 at 13:31
0

I was looking for a version that can convert deep objects, viciously nested ones.

var myObj = {
  Name: "Paul",
  Address: {
    Street: "27 Light Avenue"
    },
  City: [
    {ID:1, StateID:2, PEOPLE: ['JOHN','Franz','Dmitrj']},
        'Paris',
        {ID:3, StateID:123, PEOPLE: ['MARY','albert','PIPpo']}
  ]
}

console.log(JSON.stringify(myObj,null,4))

function ConvertKeysToLowerCase(obj) {
    if (Object.prototype.toString.apply(obj) !== '[object Array]' && Object.prototype.toString.apply(obj) !== '[object Object]') {
        return obj;
    }
    let output = {};
    for (let i in obj) {
        if (Object.prototype.toString.apply(obj[i]) === '[object Object]') {
           output[i.toLowerCase()] = ConvertKeysToLowerCase(obj[i]);
        } else if(Object.prototype.toString.apply(obj[i]) === '[object Array]'){
            output[i.toLowerCase()]=[];
            for (let j = 0; j < obj[i].length; j++) {
                output[i.toLowerCase()].push(ConvertKeysToLowerCase(obj[i][j]));
            }
        } else {
            output[i.toLowerCase()] = obj[i];
        }
    }
    return output;
};

const newObj = ConvertKeysToLowerCase(myObj)

console.log(JSON.stringify(newObj,null,4))

I modified the answer from a duplicated question on this topic, https://stackoverflow.com/a/36280878/11994902, that is buggy and doesn't really convert arrays.

Sotis
  • 176
  • 1
  • 9
0

Use json-case-convertor

const jcc = require('json-case-convertor')
const lowerCase = jcc.lowerCaseKeys({"ID":1234, "CONTENT":"HELLO"})

Link to package: https://www.npmjs.com/package/json-case-convertor

SWIK
  • 714
  • 7
  • 12