Adding to a JSON string - javascript

I have a JSON string as follows:
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
It is generated after calling this function in KnockOut:
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.product() ? {
TypeName: line.category().TypeName,
TypeID: line.category().TypeID
: undefined
});
alert(JSON.stringify(dataToSave));
However, I want to add 3 more pieces of information to the model, before posting it back to my server - to also send Name, Email and Tel:
{
"Name":"Mark",
"Email":"me#me.com",
"Tel":"0123456789",
"Rooms":
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
}
Is there a proper way of adding this information to the JSON, or is it just as simple as:
var toSend = "{\"Name\":\"Mark\":\"Email\":\"me#me.com\", \"Tel\":\"0123456789\",\"Rooms\":"
+ JSON.stringify(dataToSave) + "}";
Thank you,
Mark

Parse your JSON string using JSON.parse into a valid JS object, add the data to the object as needed, then JSON.stringify it back. A JSON string is just a representation of your data, so you shouldn't rely on modifying it directly.

Why encode to JSON and then modify the resulting string when you can pass the structure you actually want to the JSON encdoder?
var toSend = JSON.stringify({
Name: "Mark",
Email: "me#me.com",
Tel: "0123456789",
Rooms: dataToSave
});

Related

Json parse not convert to object

My API return user object and format is like that=>
{'id': '1', 'username': 'admin', 'image': 'https://user/testing.png', 'phno': '123'}
First I do JSON.stringify and I check the type of this line is a string.
So I use JSON.parse to get an object but its still string and can't get it likes user.id is undefined.
How can I get like user.id, user.username,...?
console.log(user);
console.log(user.user);
var test = JSON.stringify(user.user);
console.log(typeof(test));
var test1 = JSON.parse(test);
console.log(test1.id);
I think the problem might be that your API is returning JSON data with single quotation marks, and JavaScript is not able to parse it correctly. Check which JSON serializer you're using on server side. It should be like: {"id": "1", "username": "admin", "image": "https://user/testing.png", "phno": "123"}.
This solution works for your data:
var data = '{"id": "1", "username": "admin", "image": "https://user/testing.png", "phno": "123"}';
var user = JSON.parse(data);
console.log(user.id);
It seems like you are not getting exact user json. Issue may be backend.
const obj = `{"user":"{\\"id\\": \\"1\\", \\"username\\": \\"admin\\", \\"image\\": \\"https://user/testing.png\\", \\"phno\\": \\"123\\"}"}`
console.log(obj)
// First get value of user.
let user = JSON.parse(obj).user
console.log(typeof user) //string
// parse again, since user is string
user = JSON.parse(user)
console.log(user.username)
console.log(user.id)

JS - atob() The string to be decoded contains invalid characters

I'm having some string conversion issues in JS. I have a json object that I want to base64 encode and store as a client side cookie. It seems simple enough but for some reason the JS atob is just not working for me. I keep getting this error
InvalidCharacterError: The string to be decoded contains invalid characters.
Here is a simplified version of why I'm trying to accomplish:
function setCookie(name, value, days) {
var d = new Date;
d.setTime(d.getTime() + 24*60*60*1000*days);
document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}
function getCookie(name) {
var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
function getUser() {
let user = getCookie('ds_user')
if (!user) {
return null
}
return JSON.parse(atob(user))
}
const mockUser = {
user: {
id: "1671",
email: "artvandalay#industries.com",
username: "art",
firstName: "Art",
lastName: "Vandalay",
phone: null,
admin: true,
title: "",
guid: "u0000ZDCF4",
vendorUser: false,
lastLogin: "2019-06-07 18:52:11",
defaultStoreId: "6",
},
store: {
storeId: 6,
name: "Demo Store",
marketId: 13
}
}
setCookie('ds_user', JSON.stringify(btoa(mockUser)), 7)
console.log(getUser())
My fiddle: https://jsfiddle.net/u1zjsqyn/
I have tried following other solutions from similar posts like https://stackoverflow.com/a/9786592/5025769 , but no luck
mockUser is an object, when you do btoa(mockUser) you end up with [Object, object], the string version of any object, as btoa can't parse objects.
You want to stringify the object before converting to Base64, then when you get the data back, you do what you're doing, decode Base64 first, then parse as object.
setCookie('ds_user', btoa(JSON.stringify(mockUser)), 7)
FIDDLE

why does PHP json_encode ignore empty arrays?

I have the following javascript that sends data to a PHP function:
<script>
var mydata = {
id:123,
name: 'mike',
orders: []
};
$.ajax({
type: 'POST',
url: 'test.php',
data: {save_data:mydata},
success: function(data) {
alert('php received: ' + data);
}
});
</script>
and my test.php file contains the following code:
<?php
if (isset($_POST['save_data'])) {
$json = json_encode($_POST['save_data']);
echo $json; // just to check what has been received
exit();
}
?>
What I expect to received from PHP is:
{"id":"123","name":"mike","orders":"[]"}
What I got back is {"id":"123","name":"mike"}
Notice that orders array has been eliminated from the output. No place holder for it. I tried adding some dummy elements in the array, and that worked fine, and I received the array back with the elements.
I need PHP to receive the json object as is, even if it contains empty arrays.
How can I do that?
The JSON object is created inside PHP. Before then you just have form data.
jQuery will encode form data in a PHP-friendly style.
If you give it:
data: { foo: [1, 2, 3] }
It will convert that to:
foo[]=1&foo[]=2&foo[]=3
(although it will percent encode the [])
You get a key=value pair for each value.
If you have an empty array then you don't have any values, so you don't get any key=value pairs.
There is no way to encode "an empty array" using PHP's extensions to the form url encoding syntax.
You have two basic options:
Tell PHP about what data structure you want to create in advance and have it fill in the empty arrays.
Generate the JSON on the client
It is not error of PHP. It cause by Jquery will igrone empty array when send it to server. So you have to parse array in 'orders' key to string JSON before send
var mydata = {
id:123,
name: 'mike',
orders: []
};
Change to
var mydata = {
id:123,
name: 'mike',
orders: JSON.stringify([])
};

Manipulate ajax response

I have a ajax post method. I get an object from the backend
$.ajax({
type: "POST",
url: URL_one,
data: submitData
}).then(function (response) {
console.log("Ajax response", response);
});
and when i do a console.log(response); inside the post method, i see the following data.
>Object{Info:Array[200]}
>Info:Array[200]
>[0-99]
>0:Object
name:'Ashley'
on_pay: true
valid:"0"
>[100-199]
So each array has objects like one mentioned above with name, on_pay and valid. I want to do the following
Since all on_pay values are true in my case, i need to convert it to false. Also valid has string of 0. I need to put all values as blank instead of 0.
Is it possible to do ?? Can someone please shed some light on these.
Considering the JSON structure that you show, following should work to change the on_pay value:
response.Info.forEach(function(item){
item.on_pay = false;
});
If I'm understanding your question correctly, response is an array of items. You want to keep those items intact, but turn the on_pay property false and valid to an empty string.
You can use Array::map() to transform each item.
/*jslint node:true*/
"use strict";
// I am assuming your response looks something like this
var response = {
Info: [
{
name: "Ashley",
on_pay: true,
valid: "0"
},
{
name: "Jim",
on_pay: true,
valid: "0"
},
{
name: "John",
on_pay: true,
valid: "0"
}
]
};
// This will produce a new variable that will hold the transformed Info array
var fixedResponseInfo = response.Info.map(function (item) {
item.on_pay = false;
item.valid = "";
return item;
});
// This will edit the response.Info array in place
response.Info.forEach(function (item) {
item.on_pay = false;
item.valid = "";
});
console.log(fixedResponseInfo);
console.log(response);
This will keep your original response variable and produce a new variable fixedResponseInfo that contains the transformed array. If you don't care whether data in response is changed, you can use Array::forEach() to iterate instead.

JSON.stringify set root element

I want to convert my object into a JSON String where the root element should be the name of my object.
var data = {
name: 'qwertz',
age: 23,
skills: [
'html', 'css'
]
}
var json = JSON.stringify(data);
The output is:
{"name":"qwertz","age":23,"skills":["html","css"]}
But I want this:
{"data":{"name":"qwertz","age":23,"skills":["html","css"]}}
Can someone give me a hint how to reach this? Thanks you :)
As simple as that:
var json = JSON.stringify({ data: data });
Try this
JSON.stringify({'data':data})

Categories

Resources