13

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?

6
  • is this part of your script or page itself ? Commented Feb 1, 2015 at 14:40
  • What have you tried and why is it your guess that you need to use those functions? Commented Feb 1, 2015 at 14:48
  • @vishalsharma This part is on page itself. Commented Feb 1, 2015 at 15:14
  • @paul Because I looked on the web? Commented Feb 1, 2015 at 15:15
  • this is just an object so you can use unsafeWindow.page.btn.eye = "green"; Commented Feb 1, 2015 at 15:22

4 Answers 4

16

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"');
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
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.

1 Comment

I am not able to replace it like this
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'))))

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.