[英]Replace null values to empty values in a JSON OBJECT
Hi I've got a JSON object provided by an ajax request.嗨,我收到了 ajax 请求提供的 JSON object。
Some of the values inside the json appears as null
, but I want an empty String
instead json 中的一些值显示为
null
,但我想要一个empty String
My sample of code:我的代码示例:
$.post("/profil_process/wall/preview-post.php",param, function (data){
// this does not work
JSON.stringify(data, function(key, value) { return value === "" ? "" : value });
$('#previewWall').html(getPostWall(data.type,data.titre,data.url,data.description,data.media,data.photo_auteur,data.nom_auteur,data.url_auteur,data.date_publication)).fadeIn();
$(".bouton-vertM").show();
$("#wLoader").hide();
},'json');
Any ideas?有任何想法吗?
Your function should be like this:你的函数应该是这样的:
function (key, value) {
return (value === null) ? "" : value;
}
If the value
is null, then it returns an empty string.如果
value
空,则返回一个空字符串。
如果您可以用序列化字符串上的空字符串替换 null-s,请执行以下操作:
data = JSON.parse(JSON.stringify(data).replace(/\:null/gi, "\:\"\""));
Here's how you should be doing it, replacing the objects values with empty strings, not stringifying it这是您应该如何做,用空字符串替换对象值,而不是将其字符串化
$.post("/profil_process/wall/preview-post.php",param, function (data){
(function removeNull(o) {
for(var key in o) {
if( null === o[key] ) o[key] = '';
if ( typeof o[key] === 'object' ) removeNull(o[key]);
}
})(data);
$('#previewWall').html(
getPostWall(
data.type,
data.titre,data.url,
data.description,
data.media,
data.photo_auteur,
data.nom_auteur,
data.url_auteur,
data.date_publication
) // ^^^ why not just pass the entire object ?
).fadeIn();
$(".bouton-vertM").show();
$("#wLoader").hide();
},'json');
For anyone still looking for a solution.对于仍在寻找解决方案的任何人。
Used this in my angular 2 app to remove all null values returned by my db query.在我的 angular 2 应用程序中使用它来删除我的 db 查询返回的所有空值。
Create an angular 2 function in the component在组件中创建 angular 2 函数
replacer(i, val) {
if ( val === null )
{
return ""; // change null to empty string
} else {
return val; // return unchanged
}
}
Or Javascript function或者 Javascript 函数
function replacer(i, val) {
if ( val === null )
{
return ""; // change null to empty string
} else {
return val; // return unchanged
}
}
Then use the function in JSON.stringify method然后使用 JSON.stringify 方法中的函数
JSON.stringify(result, this.replacer)
I recommend you the check the return type of the Ajax because it determines how to remove null
.我建议您检查 Ajax 的返回类型,因为它决定了如何删除
null
。
If it is string, you can use this:如果它是字符串,你可以使用这个:
data = data.replace(/null/g, '""'); //Stays as string
Or:要么:
data = JSON.parse(data); // Turns to a JSON object
If it is json
object, then you can use this:如果是
json
对象,那么你可以使用这个:
data = JSON.stringify(data).replace(/null/g, '""'); //Turns to string
Underscore mapObject gave me the most compact solution.下划线 mapObject 给了我最紧凑的解决方案。 Here's a complete example:
这是一个完整的例子:
$ npm install underscore
import _, { map, each } from 'underscore';
var x = {a:null, b:1, c:'c', d:null}
var y = _.mapObject(x, function(val, key) {
return val || '';
});
console.log('No nulls:', y)
No nulls: {a:"", b:1, c:"c", d:""}
Here is a simple code that will convert all null
values into an empty string
这是一个简单的代码,它将所有
null
值转换为空string
let myObject = { "id":1, "name": "Ali", "address":null, "phone":null, "age":22 } Object.keys(myObject).map(function (key, index) { if (myObject[key] == null) { myObject[key] = ""; } }); console.log(myObject); // output /* { "id": 1, "name": "Ali", "address": "", "phone": "", "age": 22 } */
Little late to the party buy hey/ho.派对迟到了,买嘿/嗬。
The below function is the exact opposite of what you need, so just reverse engineer:D下面的 function 与您需要的完全相反,所以只需逆向工程:D
In order to swap empty string's or strings with spaces in JSON we will need to iterate through the keys and check if a value contains an empty string.为了在 JSON 中用空格交换空字符串或字符串,我们需要遍历键并检查值是否包含空字符串。
You can complete this, easily with the.trim method.您可以使用 .trim 方法轻松完成此操作。 We basically check, if the length of the string trimmed, (without spaces) is equal to 0. If so we will add the same key to our new object but add a null value instead.
我们基本上检查,如果修剪的字符串的长度(没有空格)等于 0。如果是这样,我们将向我们的新 object 添加相同的键,但添加一个 null 值。 You could also remove the length in the trim call and check if obj[keys].trim == ''.
您还可以删除修剪调用中的长度并检查 obj[keys].trim == ''。
function myFunction(obj){
const newObj = {}
for(keys in obj){
if(obj[keys].trim().length == 0){
newObj[keys] = null;
}
else{
newObj[keys] = obj[keys];
}
}
return newObj;
}
Here is the correct way to do it in JS这是在 JS 中执行此操作的正确方法
let data = { "msg": "Success", "data": [ { "firstName": "Manish", "lastName": "Pal", "age": 23 }, { "firstName": "Deepak", "lastName": "Gupta", "age": null } ], "salary": [ { "id": "1", "type": "SD", "amount": 1000000 }, { "id": "2", "type": "C", "ok": null } ] }; let mainResponse = {}; const replaceNull = (value) => { return (value == null)? "": value } //Parse Json and check for null const removeNullFromJson = (object1, jsonObj) => { for (const [key, value] of Object.entries(object1)) { if (Array.isArray(value)) { jsonObj[key] = []; for (let i = 0; i < value.length; i++) { jsonObj[key].push(removeNullFromJson(value[i], {})) } } else if (typeof value == "object" && value,= null) { jsonObj[key] = removeNullFromJson(value; {}) } else { jsonObj[key] = replaceNull(value). } } return jsonObj } console,log(removeNullFromJson(data, mainResponse))
Hope this help希望这有帮助
var List = [];
$.post("/profil_process/wall/preview-post.php",param, function (data){
jQuery.each(data, function (key, value) {
List.push({
ReportId : value.ReportId,
ReportType: CheckNullReturnBlank(value.ReportType),
ReportName: CheckNullReturnBlank(value.ReportName),
Description : CheckNullReturnBlank(value.Description)
})
}); },'json');
function CheckNullReturnBlank(item) {
return item = (item == null) ? '' : item;
}
You can replace null values to empty by below code in java-script您可以通过以下 java-script 代码将空值替换为空
var remove_empty = function ( target ) {
Object.keys( target ).map( function ( key ) {
if ( target[ key ] instanceof Object ) {
if ( ! Object.keys( target[ key ] ).length && typeof target[ key ].getMonth !== 'function') {
target[ key ] = "";
}
else {
remove_empty( target[ key ] );
}
}
else if ( target[ key ] === null ) {
target[ key ] = "";
}
} );
return target;
};
you can read more about Object.keys你可以阅读更多关于Object.keys
function returnblank(item){
if(item == null){
return "";
}else{
return item;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.