Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace the text in JSON string with a userscript for Greasemonkey

I want to create a user script for Greasemonkey in Firefox without using jQuery, which can replace old text by new text when the page of website is loaded.

HTML code:

..

window.app = profileBuilder({
..
    "page": {
        "btn": {
            "eye": "blue",
            "favorite_color": "blue",
            "gender": "male",
        },
    },
..
});

..

Replace "blue" of eye by "green", "blue" of favorite color by "red" and "male" by "female".

When the page will be loaded, I want to see, for instance Green (not Blue) for Eye and Female for Gender (not Male).

I guess I need to use functions next:

GM_getValue()
GM_setValue()
JSON.parse()
JSON.stringify()

PS: the code JSON is directly in the page and not in file (../code.json)

Userscript code:

// ==UserScript==
// @name        nemrod Test
// @namespace   nemrod
// @include     http*://mywebsite.com/*
// @version     1
// ==/UserScript==
var json = {"page": {"btn": {"eye": "blue","favorite_color": "blue","gender": "male",},},};
var stringified = JSON.stringify(json);
stringified = stringified.replace(/"eye": "blue"/gm, '"eye": "green"');
stringified = stringified.replace(/"favorite_color": "blue"/gm, '"favorite_color": "red"');
var jsonObject = JSON.parse(stringified);

It doesn't work

Can somebody help with the right code?

like image 570
nemrod Avatar asked Feb 01 '15 14:02

nemrod


2 Answers

First iteration - JSON.stringify

var json = {"page": {"btn": {"eye": "blue","favorite_color": "blue","gender": "male"}}};

var replaceBy = {
  eye: function(value) {
    if (value == 'blue') {
      return 'green'
    }
  },
  favorite_color: function(value) {
    if(value == 'blue') {
      return 'red'
    }
  },
  gender: function(value) {
    if(value == 'male') {
      return 'female'
    }
  }
}

console.log(JSON.stringify(json, function(key, value) {
  if(replaceBy[key]) {
    value = replaceBy[key](value)
  }
  return value
}))

Second iteration - be nice for ES Harmony

  • add rule - adds strict comparison
  • add matcher - adds any function that is responsible for data matching / replacing

'use strict'

var json = {
  "page": {
    "btn": {
      "eye": "Blue",
      "favorite_color": "blue",
      "gender": "male"
    }
  }
};

class Replacer {
  constructor() {
    this.matchers = []
  }

  addRule(rule, source, destination) {
    this.matchers.push({
      type: rule,
      matcher: value => value == source ? destination : value
    })
    return this
  }

  addMatcher(type, matcher) {
    this.matchers.push({
      type: type,
      matcher: matcher
    })
    return this
  }

  getByType(type) {
    return this.matchers.find(matcher => matcher.type === type)
  }

  applyRuleFor(type, value) {
    if (this.getByType(type)) {
      return this.getByType(type).matcher(value)
    }
  }

  static replaceWith(replacer) {
    return (key, value) => {
      if (replacer.getByType(key)) {
        value = replacer.applyRuleFor(key, value)
      }
      return value
    }
  }
}

console.log(JSON.stringify(json, Replacer.replaceWith(new Replacer()
  .addMatcher('eye', (value) => value.match(/blue/i) ? 'green' : value)
  .addRule('favorite_color', 'blue', 'red')
  .addRule('gender', 'male', 'female'))))
like image 170
Krzysztof Safjanowski Avatar answered Sep 16 '22 19:09

Krzysztof Safjanowski


more accurate procedure would be to use regular expression.

   stringified.replace(/"eyes":"blue"/gm, '"eyes":"blue"')

this way you know you're replacing the blue for eyes and not any blue appearing (like favorite color). the 'g' & 'm' options for regular expression stands for global which will cause searching for all applicable matches (in case you have more than one 'eyes' in your json) and 'm' for multiline. in case your string is multilined.

like image 22
Gal Ziv Avatar answered Sep 16 '22 19:09

Gal Ziv