How to concatenate string and numbers to make a JSON object? - javascript

I want to make a JSON object like this:
let lob = { courses_dept: 'sci', courses_avg: 77.09 };
by concatenate variables together:
var dept = "sci";
var avg = 77.09;
let a = '{"courses_dept": dept, "courses_averge": avg }';
but I got SyntaxError if I do this:
let b = JSON.parse(a);
What is the proper way to do this?

Note JSON stands for JavaScript Object Notation. JSON is always a string. It is a string representation of your encoded data. There is no such thing as "a JSON Object".
Don't attempt to write JSON by joining strings and other values together. Instead build an object and pass it to JSON.stringify -
const dept = "sci"
const avg = 77.09
// make an object
const myobject = { courses_dept: dept, courses_average: avg }
// use JSON.stringify to encode myobject to JSON
const myjson = JSON.stringify(myobject)
console.log("encoded", myjson)
// test JSON.parse to decode the JSON and get the object back
console.log("decoded", JSON.parse(myjson))
encoded {"courses_dept":"sci","courses_average":77.09}
decoded {
"courses_dept": "sci",
"courses_average": 77.09
}

If you want to use strings:
var dept = "sci";
var avg = 77.09;
let a = `{"courses_dept": "${dept}", "courses_averge": ${avg} }`;
This assumes that dept is a string. If you don't know this in advance, wrap each variable with JSON.stringify:
let b = `{"courses_dept": ${JSON.stringify(dept)}
,"courses_averge": ${JSON.stringify(avg)}}`;
Notice that the string uses backticks ` instead of regular quotes. This allows you to do string interpolation. You can use + if you want to do straight up concatenation.
You can also just do a regular object:
let c = {"courses_dept": dept, "courses_averge": avg}
JSON.stringify(c)

Why not just plain json object then?
var dept = "sci";
var avg = 77.09;
let a = {
"courses_dept": dept,
"courses_averge": avg
};
console.log('a', a);

This way works and seems to be simpler.
let b = {};
b["courses_dept"] = dept;
b["courses_averge"] = avg;

You can make a JSON with single quotes and concatenate variables. After that you can parse the string.
var id_of_the_product = $('#is-a-gift').data( 'gift_product_id' ) ;
var items_in_cart = (cart_item_count) - (gift_wraps_in_cart);
$.ajax({
type: 'POST',
url: '/cart/update.js',
data: JSON.parse('{ "updates": { "'+ id_of_the_product +'" : "'+items_in_cart+'" }, "attributes": { "gift-wrapping": "'+gift_wrapping_type+'" } }'),
dataType: 'json',
success: function() { }
});

Related

Convert to String Format

I Have a string like
[ "Basic, JavaScript, PHP, Scala" ]
How to convert it like
[ 'Basic', 'JavaScript', 'PHP', 'Scala' ]
code
function loadDataToGridChiefComplaint() {
var tHRNo = document.getElementById("lblpthrno").value;
var tOPDNo = document.getElementById("lblptopd").value;
var localKeyChief = tHRNo + '-' + tOPDNo + '-ChiefComplaint';
var a = localStorage.getItem(localKeyChief);
var Item = JSON.stringify(a); // it show like ["Basic, JavaScript, PHP, Scala"]
}
JSON.stringify() returns a String so your question is incorrect. Item is not an Array.
const Item = '["Basic, JavaScript, PHP, Scala"]';
Therefore you should not use it. Instead simply return the array a in your function:
function loadDataToGridChiefComplaint() {
var tHRNo = document.getElementById("lblpthrno").value;
var tOPDNo = document.getElementById("lblptopd").value;
var localKeyChief = tHRNo + '-' + tOPDNo + '-ChiefComplaint';
return localStorage.getItem(localKeyChief); // <-- no use of JSON.stringify()
}
This way loadDataToGridChiefComplaint() is the array ["Basic, JavaScript, PHP, Scala"], it has a single element of type String that you can access with the bracket notation Item[0]:
const Item = ["Basic, JavaScript, PHP, Scala"];
console.log(Item[0]);
So in order to convert the string Item[0] into an array, use the .split method:
String.split(separator)
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
MDN Web Docs
const Item = ["Basic, JavaScript, PHP, Scala"];
console.log(Item[0].split(', '));
If you can't modify this function you can use the opposite operation of JSON.stringify which is JSON.parse to convert the string back to an array:
const ItemString = '["Basic, JavaScript, PHP, Scala"]';
ItemArray = JSON.parse(ItemString);
And then use .split (like the previous example) to get the array of strings.
Try this :
var Item = ["Basic, JavaScript, PHP, Scala"];
// Do like this
var array = Item[0].split(', '); // Split with Comma and space(for trim whitespace)
// Or Like this
var array = Item[0].split(',').map(i => i.trim()) // Split with comma and use map to trim whitespace
console.log(array);

convert string to object key more than 2depths

I want to convert string to object's key
I know this logic
const object = { name : 'test' }
const string = name
object[string] = name
I have something problems about this.
const string = common.device.type.pc.name
object[string] <- this is not working
You can do this by split string to each value
values = string.split(".");
object[values[0]][values[1]][values[2]][values[3]][values[4]]
Example:
object = {value1: {value2: "123"}};
string = "value1.value2";
values = string.split(".");
object[values[0]][values[1]] //return "123"

Converting string to object with Javascript

I am trying to convert to object this string.
"JwtBody { user_id: 1, auth_id: 1}"
"JwtBody { user_id: 1, auth_id: 1}" is obviously not a standard json string,So you can try this.
function strToObj(str){
var obj = {};
if(str&&typeof str ==='string'){
var objStr = str.match(/\{(.)+\}/g);
eval("obj ="+objStr);
}
return obj
}
Could you use JSON.parse()?
I haven't used it myself, but it looks like create a variable and use JSON.parse("string") to have it converted into an object.
So, for your example it would be something like:
var object = JSON.parse("JwtBody { user_id: 1, auth_id: 1}");
Not exactly sure what you're trying to do.
You could try something like this:
var str = '{"user_id": "1", "auth_id": "1"}';
var obj = $.parseJSON(str);
Be sure to have jquery like this:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
If you can't change data from example:
var parsedData = {};
var str = "JwtBody { user_id: 1, auth_id: 1}";
function getRawJSON(str){
return str.split(' ').map((el, index)=>{return index>0 ? el : ''}).join('');
}
function formatingValidJSON(str){
// From https://stackoverflow.com/questions/9637517/parsing-relaxed-json-without-eval
return str
.replace(/:\s*"([^"]*)"/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '#colon#') + '"';
})
.replace(/:\s*'([^']*)'/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '#colon#') + '"';
})
.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?\s*:/g, '"$2": ')
.replace(/#colon#/g, ':')
}
str = formatingValidJSON(getRawJSON(str));
try{
parsedData = JSON.parse(str);
console.log('Your parsed data:', parsedData);
}
catch(e){
console.log('Your data is wrong');
}
This JSON-like string can be parsed using vanilla JavaScript and regex by:
Reducing string to only characters that String.match() JSON-like object string
String.replace() property names to enclose matched names with quotations
parsing object with JSON.parse
var jwtBodyString = "JwtBody { user_id: 1, auth_id: 1}";
`//1 match on only JSON within string
jwtBody = jwtBodyString.match(/{[^}]+}/).toString();`
//2 enclose property names to prevent errors with JSON.parse()
jwtBody = jwtBody.replace(/([a-zA-Z]+):/g,'"$1":'));
//3 obtain object
var myJwtBodyObject = JSON.parse(jwtBody);
Use JSON.parse()
Also, you're javascript string is invalid JSON which means it's invalid javascript. It should look like this:
JSON.parse('{"jwtbody" : { "user_id" : 1, "auth_id" : 1}}');
This will give you the corresponding javascript object you want.

Why I can't parse JSON in JavaScript?

JSON contains one object:
results[0] = { 'MAX(id)': 1 }
And this code doesn't work:
var text = results[0];
var obj = JSON.parse(text);
console.log(obj.MAX(id));
results[0] is already an object type
You can parse only from string to object like this:
JSON.parse('{ "MAX(id)": 1 }');
Your object is already a JSON. You don't need to parse it.
To access MAX(id) property, you can use [] notation as follows:
results[0] = { 'MAX(id)': 1 };
console.log(results[0]['MAX(id)']);
Your result[0] is a real javascript object. JSON.parse transforms text into objects, so you can't parse other objects with it.
var results = { 'MAX(id)': 1 };
//var text = results;
//var obj = JSON.parse(text);
alert(results['MAX(id)']);

Converting a string to JSON object

How do you make JS think that a string is JSON ?
I have a function which only works if JSON object is passed to it. If I pass a string to it, with same format as JSON, it doesn't work. So I want to make that function think that the string passed to it is a JSON. The string is indeed in the JSON format.
I also tried the following. I inputted the string through Ajax , with "handle as" parameter as "JSON", and then when I passed the result to the function it works.
So I deduced the problem is not with the string. How do I convert this string to JSON? If i get same string through ajax request and then passing it to function works, whereas directly passing it doesn't work.
The string is as follows:
{
"data": [
{
"id": "id1",
"fields": [
{
"id": "name1",
"label": "joker",
"unit": "year"
},
{"id": "name2", "label": "Quantity"},
],
"rows": [ data here....
and closing braces..
var obj = JSON.parse(string);
Where string is your json string.
You can use the JSON.parse() for that.
See docs at MDN
Example:
var myObj = JSON.parse('{"p": 5}');
console.log(myObj);
I had the same problem with a similar string like yours
{id:1,field1:"someField"},{id:2,field1:"someOtherField"}
The problem here is the structure of the string. The json parser wasn't recognizing that it needs to create 2 objects in this case. So what I did is kind of silly, I just re-structured my string and added the [] with this the parser recognized
var myString = {id:1,field1:"someField"},{id:2,field1:"someOtherField"}
myString = '[' + myString +']'
var json = $.parseJSON(myString)
Hope it helps,
If anyone has a more elegant approach please share.
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
link:-
http://api.jquery.com/jQuery.parseJSON/
Simply use eval function.
var myJson = eval(theJsibStr);
convert the string to HashMap using Object Mapper ...
new ObjectMapper().readValue(string, Map.class);
Internally Map will behave as JSON Object
var Data=[{"id": "name2", "label": "Quantity"}]
Pass the string variable into Json parse :
Objdata= Json.parse(Data);
Let's us consider you have string like
example : "name:lucy,age:21,gender:female"
function getJsonData(query){
let arrayOfKeyValues = query.split(',');
let modifiedArray = new Array();
console.log(arrayOfKeyValues);
for(let i=0;i< arrayOfKeyValues.length;i++){
let arrayValues = arrayOfKeyValues[i].split(':');
let arrayString ='"'+arrayValues[0]+'"'+':'+'"'+arrayValues[1]+'"';
modifiedArray.push(arrayString);
}
let jsonDataString = '{'+modifiedArray.toString()+'}';
let jsonData = JSON.parse(jsonDataString);
console.log(jsonData);
console.log(typeof jsonData);
return jsonData;
}
let query = "name:lucy,age:21,gender:female";
let response = getJsonData(query);
console.log(response);
`
JSON.parse() function will do.
or
Using Jquery,
var obj = jQuery.parseJSON( '{ "name": "Vinod" }' );
alert( obj.name === "Vinod" );
JSON.parse() is your friend. Here's an example:
let obj = JSON.parse(yourString)
console.log(typeof obj); // prints 'object' assuming your string is correctly formatted

Categories