如何将 JSON 字符串中的文本替换为 Greasemonkey 的用户脚本

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

本文关键字:文本替换 用户 脚本 Greasemonkey JSON 字符串      更新时间:2023-09-26
我想在不使用

jQuery的情况下在Firefox中为Greasemonkey创建一个用户脚本,它可以在网站页面加载时用新文本替换旧文本。

网页代码:

..
window.app = profileBuilder({
..
    "page": {
        "btn": {
            "eye": "blue",
            "favorite_color": "blue",
            "gender": "male",
        },
    },
..
});
..
将眼睛的"蓝色"替换为"

绿色","将喜欢的颜色的"蓝色"替换为"红色",将"男性"替换为"女性"。

当页面加载时,我想看到,例如绿色(不是蓝色)代表眼睛,女性代表性别(不是男性)。

我想我接下来需要使用函数:

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

PS:代码 JSON 直接在页面中而不是在文件中(../code.json)

用户脚本代码:

// ==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);

它不起作用

有人可以帮助编写正确的代码吗?

首先stringify()你的 JSON。

var stringified = JSON.stringify(json);

接下来,使用 .replace() JavaScript 字符串函数。

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

现在,将 JSON parse()到一个对象中。

var jsonObject = JSON.parse(stringified);

现在,您可以将jsonObject用于任何您想要的用途。

编辑:使用这些行而不是以前的.replace()

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

更准确的过程是使用正则表达式。

   stringified.replace(/"eyes":"blue"/gm, '"eyes":"blue"')
通过这种方式,您

知道您正在替换眼睛的蓝色,而不是任何蓝色出现(例如最喜欢的颜色)。正则表达式的"g"和"m"选项代表全局,这将导致搜索所有适用的匹配项(如果您的 JSON 中有多个"眼睛")和多行的"m"。如果您的字符串是多行的。

第一次迭代 - 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
}))

第二次迭代 - 对 ES Harmony 友好

  • 添加规则 - 添加严格比较
  • 添加匹配器 - 添加任何负责数据匹配/替换的函数

'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字符串操作可以通过JSON.parse()JSON.stringify()轻松完成。

下面给出了一个示例示例:

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

现在,tweetString具有更新的JSON对象。