Share a JS tool: st.js - Quickly extract data from Object or convert it to another Object

Keywords: JSON Javascript github xml

Origin of this tool
Last night, I browsed the technical articles and found a good object operating tool st.js. His main role is to extract relevant data from the object (can be matched by rules), or to formulate corresponding rules to transform the object.
Looking at document st.js provides two main methods:

  1. JSON.select()
  2. JSON.transformWith()

    Both return this, so chain calls can be made.

JSON.select()

Used to extract data. We can use regularities to match key s or val.

var data = {
  "links": [
    { "remote_url": "http://localhost" },
    { "file_url": "file://documents" },
    { "remote_url": "https://blahblah.com" }
  ],
  "preview": "https://image",
  "metadata": "This is a link collection"
}
var sel = JSON.select(data, function(key, val) {
 return /https?:/.test(val);
})

We can look at the following methods of sel:
The set of keys that meet the criteria
A set of qualified values
The set of paths qualified key pairs in data
root eligible object

transformWith

Used to transform objects

var data = {
  "title": "List of websites",
  "description": "This is a list of popular websites"
  "data": {
    "sites": [{
      "name": "Google",
      "url": "https://google.com"
    }, {
      "name": "Facebook",
      "url": "https://facebook.com"
    }, {
      "name": "Twitter",
      "url": "https://twitter.com"
    }, {
      "name": "Github",
      "url": "https://github.com"
    }]
  }
}
var sel = JSON.select(data, function(key, val){
            return key === 'sites';
          })
          .transformWith({
            "items": {
              "{{#each sites}}": {
                "tag": "<a href='{{url}}'>{{name}}</a>"
              }
            }
          })

"{{each site}" can be understood as traversing every subitem of sel.sites and returning it to items after processing.

Usage method

In a browser

<script src="st.js"></script>
<script>
var parsed = JSON.select({ "items": [1,2,3,4] })
                .transformWith({
                  "{{#each items}}": {
                    "type": "label", "text": "{{this}}"
                  }
                })
                .root();
</script>

In node.js

$ npm install stjs
require('st');

var parsed = JSON.select({ "items": [1,2,3,4] })
                .transformWith({
                  "{{#each items}}": {
                    "type": "label", "text": "{{this}}"
                  }
                })
                .root();

Posted by 9999 on Fri, 08 Feb 2019 09:48:17 -0800