javascript 如何将json数据连接成字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25078340/
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-10-28 03:53:30  来源:igfitidea点击:

How to concatenate json data into string?

javascriptjqueryjson

提问by user51854

I have {"Title":"Movie1","Year":"2013"} json data. I want to get a string "Movie12013"for that json. How to achieve that?

我有{"Title":"Movie1","Year":"2013"} json数据。我想"Movie12013"为那个 json获取一个字符串。如何做到这一点?

回答by T J

If i understood correctly, you can do the following:

如果我理解正确,您可以执行以下操作:

var json= {"Title":"Movie1","Year":"2013"};
var result="";
for( key in json){
  result+= json[key];
}

You don't have to know the number of properties or it's names before hand. This should work for simple scenarios.

您不必事先知道属性的数量或其名称。这应该适用于简单的场景。

回答by hari

Demotry this,

演示试试这个,

   var json= {"Title":"Movie1","Year":"2013"};
  var append="";
  $.each(json,function(key,value){
  append+=value;
  });

回答by James Donnelly

You first need to extract the JSON data using JSON.parse():

您首先需要使用JSON.parse()以下方法提取 JSON 数据:

var data = JSON.parse(json);

This assumes your JSON data is held in a variable named jsonwhich we've passed into the parse()method. This gives us the following JavaScript object:

这假设您的 JSON 数据保存在json我们传递给parse()方法的名为的变量中。这为我们提供了以下 JavaScript 对象:

{
    Title: "Movie1",
    Year: "2013"
}

We can now join the two values simply by concatenating them with the +symbol:

我们现在可以简单地通过将它们与+符号连接来连接两个值:

var result = data.Title + data.Year; // "Movie12013"

回答by user468891

try something like this

尝试这样的事情

var jsonText = '{"Title":"Movie1","Year":"2013"}'
obj = JSON.parse(jsonText);
var string = obj.Title + obj.Year;

回答by cgf

Assuming the JSON data is kept in a jsonVarNamevariable:

假设 JSON 数据保存在一个jsonVarName变量中:

jsonVarName.title + jsonVarName.year