12

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?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
nemrod
  • 129
  • 1
  • 1
  • 6

4 Answers4

15

First stringify() your JSON.

var stringified = JSON.stringify(json);

Next, use the .replace() JavaScript String function.

stringified = stringified.replace('"eye": "blue"', '"eye": "green"');
stringified = stringified.replace('"gender": "male"', '"gender": "female"');

Now parse() your JSON into an object.

var jsonObject = JSON.parse(stringified);

Now, you can use jsonObject for whatever you want.

EDIT: Use these lines instead of the previous .replace()s.

stringified = stringified.replace('"eye": "blue"', '"eye": "green"');
stringified = stringified.replace('"gender": "male"', '"gender": "female"');
Anirudh Ajith
  • 887
  • 1
  • 5
  • 15
  • Can I use a regex ? Like /"eye": "(d+)"/g replace "eye": "green", because if I have "favorite_color": "blue" we can see 2 time the same color. – nemrod Feb 01 '15 at 15:53
  • You could but I think the `.replace()` String function is more straightforward right now since it is provided in JavaScript anyway. You could use RegEx too if you want to. – Anirudh Ajith Feb 01 '15 at 15:55
2

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.

Gal Ziv
  • 6,890
  • 10
  • 32
  • 43
1

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'))))
Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47
0

JSON string manipulation can be done easily with JSON.parse() and JSON.stringify().

A sample example is given below:

var tweet = '{ "event": { "type": "message_create", "message_create": { "target": { "recipient_id": "xx_xx" }, "message_data": { "text": "xxx_xxx" } } } }';

var obj = JSON.parse(tweet);
obj.event.message_create.target.recipient_id = Receiver;
obj.event.message_create.message_data.text = statusText;

var tweetString = JSON.stringify(obj);

Now the tweetString has the updated JSON object.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38