最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert json object to string and replace text - Stack Overflow

programmeradmin0浏览0评论

I would like to convert my json to a string then find and replace substrings like so using JQuery

var data = JSON.stringify(object).text();
data.text(data.replace("meat", "vegetables"));
console.log(data);

This gives me

JSON.stringify(...).text is not a function

How can I fix this.

I would like to convert my json to a string then find and replace substrings like so using JQuery

var data = JSON.stringify(object).text();
data.text(data.replace("meat", "vegetables"));
console.log(data);

This gives me

JSON.stringify(...).text is not a function

How can I fix this.

Share edited Sep 8, 2017 at 20:12 Stuwart asked Sep 8, 2017 at 19:31 StuwartStuwart 32 silver badges6 bronze badges 5
  • For future reference: there is a JavaScript object, and then there is its JSON (string) representation. There isn't anything called a JSON object. – Andy Commented Sep 8, 2017 at 19:38
  • @Andy I also feel that you're right, but check those examples – James Commented Sep 8, 2017 at 19:48
  • @Andy JSON stands for javascript object notation, yes there isn't such thing as a JSON object as that would be javascript object notation object. But I think everyone understands what I meant when I said JSON object. See here: w3schools./js/js_json_objects.asp – Stuwart Commented Sep 8, 2017 at 19:51
  • Yes. But the issue is that you didn't understand that because you wanted to convert something that was already JSON into a string - you were using confusing terminology, either from something you read, or from a colleague etc. I'm saying the best way to stop making that error is to elimnate the term altogether. – Andy Commented Sep 8, 2017 at 19:56
  • @Andy point taken – Stuwart Commented Sep 8, 2017 at 20:11
Add a ment  | 

2 Answers 2

Reset to default 3

JSON.stringify is already a text (string), that's what stringify means (turn to a string), just omit the .text():

var object = {"food":"meat","quantity":"10"}
var data = JSON.stringify(object); // this is a string
data = data.replace("meat", "vegetables");
console.log(data);

The method stringify returns string and the type string doesn't have the method text, so just update the first line to the following:

 var data = JSON.stringify(object);

also update the second line with the following:

data = data.replace("meat", "vegetables");
发布评论

评论列表(0)

  1. 暂无评论