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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28263868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:30:47  来源:igfitidea点击:

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

javascripthtmljsonreplaceuserscripts

提问by nemrod

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.

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

HTML code:

HTML代码:

..

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)

PS:代码JSON直接在页面中而不是在文件中(../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?

有人可以帮助提供正确的代码吗?

回答by Anirudh Ajith

First stringify()your JSON.

首先是stringify()你的 JSON。

var stringified = JSON.stringify(json);

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

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

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

Now parse()your JSON into an object.

现在parse()你的 JSON 变成了一个对象。

var jsonObject = JSON.parse(stringified);

Now, you can use jsonObjectfor whatever you want.

现在,您可以随意使用jsonObject

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

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

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

回答by Gal Ziv

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.

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

回答by Krzysztof Safjanowski

First iteration - JSON.stringify

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

第二次迭代 - 对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'))))

回答by Dhanya Gopinath

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

JSON使用JSON.parse()和可以轻松完成字符串操作 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 tweetStringhas the updated JSONobject.

现在tweetString有更新的JSON对象。