最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to parse JSON to object with lower case key - Stack Overflow

programmeradmin1浏览0评论

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

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"}
Share Improve this question asked Feb 4, 2013 at 23:01 SwiftMangoSwiftMango 15.3k14 gold badges77 silver badges138 bronze badges 4
  • 1 Perhaps this could be of use? stackoverflow.com/questions/9421556/… – Eric Hotinger Commented Feb 4, 2013 at 23:03
  • @EricHotinger The data is very large... I am not sure if it is good performance. I am thinking there might be some other way to do it while parsing – SwiftMango Commented Feb 4, 2013 at 23:04
  • You forgot to quote HELLO. – Fabrício Matté Commented Feb 4, 2013 at 23:05
  • see: stackoverflow.com/questions/12539574/… – Nirvana Tikku Commented Feb 4, 2013 at 23:15
Add a comment  | 

7 Answers 7

Reset to default 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/

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:

  • jQuery.each
  • String.toLowerCase

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"}'))

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.

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

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>

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

发布评论

评论列表(0)

  1. 暂无评论