How to parse or query complex JSON in JavaScript

2019-01-26 00:49发布

Is it possible to perform complex queries over a JSON object? I am open to JavaScript or jQuery solutions, the easier the better. I'm envisioning some kind of functional programming language similar to LINQ or SQL.

I Prefer no other third party libraries or add-ons.

UPDATE
From the looks of early answers, an add-on is going to be necessary. In that case, I prefer an add-on that requires no installation process. Something that deploys with the software publish (like jQuery) is fine (e.g. sets of *.js files).

4条回答
戒情不戒烟
2楼-- · 2019-01-26 01:40

By the time you're interacting with it, it's not a "JSON object," it's a JavaScript object. ("JSON objects" only exist in terms of the data notation.) JavaScript itself doesn't have any advanced functional programming constructs, so you'd need third party libraries for that sort of thing. JavaScript pretty much just has property accessors, an operator for "does this object have a property with this name?" (in, hasOwnProperty), and as of the 5th edition (not yet widely supported), some handy array-specific features like forEach, every, map, filter, and the like.

查看更多
时光不老,我们不散
3楼-- · 2019-01-26 01:43

hmm... YQL does this sort of thing, but that would be a third party.

you could filter an array with the jQuery $.grep(array,filterfn) method

 var newArr = $.grep(oldArr,function(elInArray,index){
   return elInArray.key === somevalue;
 });

and you can of course use a regexp in there if you wish, or use more complex conditions, such as checking multiple keys, keys within keys, arrays within keys, etc.

查看更多
在下西门庆
4楼-- · 2019-01-26 01:45

Use JSON.stringify and a replacer callback to achieve this:

function replacer(match, offset, fullstring)
  {
  return replacer.str;
  }

replacer.str = "\u0022filterValues\u0022:[\u0022hi\u0022,\u0022bye\u0022]"; /* Use DOM node value */

var foo = JSON.stringify({
"Region": {
    "filterField": "kw_Region",
    "filterValues": [
        "aa",
        "bb"
    ]
},
"ApplicationName": {
    "filterField": "kw_ApplicationName",
    "filterValues": [
        "aa",
        "bb"
    ]
},
"IssueType": {
    "filterField": "kw_IssueType",
    "filterValues": [
        "aa",
        "bb"
    ]
},
"Outage": {
    "filterField": "kw_Outage",
    "filterValues": [
        "aa",
        "bb"
    ]
},
"Priority": {
    "filterField": "kw_Priority",
    "filterValues": [
        "aa",
        "bb"
    ]
}
}).replace(/"filterValues[^\]]+./g, replacer)

Here is some documentation on the two JSON methods for serialization and transformation, stringify and parse:

JSON.parse(source, reviver)

This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception.

The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted.

The reviver is ultimately called with the empty string and the topmost value to permit transformation of the topmost value. Be certain to handle this case properly, usually by returning the provided value, or JSON.parse will return undefined.

 if (k === "") return v

JSON.stringify(value, replacer, space)

The stringify method produces a JSON text from a JavaScript value. If value is an object or array, the structure will be visited recursively to determine the serialization of each membr or element. The structure must not be cyclical.

When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the object holding the key.

You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization.

If the replacer parameter is an array, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified.

Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined.

The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read.

If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces.

var alias = {"Clark":"","phone":""};

function kryptonite(key)
   {
   var replacement = {};
   for(var cursor in this)
     {
     if(cursor in alias)
       replacement[cursor] = this[cursor]
     }

   return replacement;
   }

var contact = {
               "Clark":"Kent",
               "Kal El":"Superman",
               "phone":"555-7777"
              }

contact.toJSON = kryptonite;
var foo = JSON.stringify(contact) // "{"Clark":"Kent","phone":"555-7777"}"

References

查看更多
萌系小妹纸
5楼-- · 2019-01-26 01:50
登录 后发表回答