admin管理员组

文章数量:1182280

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/*
// @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?

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?

Share Improve this question edited Feb 1, 2015 at 19:58 AstroCB 12.4k20 gold badges58 silver badges74 bronze badges asked Feb 1, 2015 at 14:38 nemrodnemrod 1391 gold badge1 silver badge6 bronze badges 6
  • is this part of your script or page itself ? – Vishal Sharma Commented Feb 1, 2015 at 14:40
  • What have you tried and why is it your guess that you need to use those functions? – Paul Commented Feb 1, 2015 at 14:48
  • @vishalsharma This part is on page itself. – nemrod Commented Feb 1, 2015 at 15:14
  • @paul Because I looked on the web? – nemrod Commented Feb 1, 2015 at 15:15
  • this is just an object so you can use unsafeWindow.page.btn.eye = "green"; – Vishal Sharma Commented Feb 1, 2015 at 15:22
 |  Show 1 more comment

4 Answers 4

Reset to default 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"');

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.

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'))))

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.

本文标签: javascriptHow can I replace the text in JSON string with a userscript for GreasemonkeyStack Overflow