javascript JSON stringify 返回空字符串

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

JSON stringify returns empty string

javascriptarraysjsonstring

提问by Jens T?rnell

In Javascript I try to use stringify but it keeps returning an empty string. What is wrong here? Feel free to edit the Fiddle.

在 Javascript 中,我尝试使用 stringify,但它一直返回一个空字符串。这里有什么问题?随意编辑小提琴。

JS

JS

values = [];
values['belopp'] = 2322;
values['test'] = 'jkee';

str = JSON.stringify(values);

console.log(values);
console.log(str); // Expected to show a json array

JS Fiddle

JS小提琴

https://jsfiddle.net/L4t4vtvd/

https://jsfiddle.net/L4t4vtvd/

回答by vjdhama

You are trying to use something that is meant for an object on an array.

您正在尝试使用用于数组上的对象的内容。

values = {};
values['belopp'] = 2322;
values['test'] = 'jkee';

str = JSON.stringify(values);

This is the updated fiddle.

这是更新的小提琴

回答by Kutyel

You are stringifying an array ([]), not an object ({})Therefore, values = {};

你是字符串化一个array ([]),而不是一个object ({})因此,values = {};