Cannot get two objects united with Json.parse and Json.stringify - javascript

I have a doubt about how to unite to objects and give them in a express response in node js.
The object is like this:
{
"idP": 1,
"pasaporteNum": 787643682,
"fidP": 1,
"fid_p": 1
}
The other one also:
{
"idP": 1,
"pasaporteNum": 827348,
"fidP": 1,
"fid_p": 75683475
}
So the code is something like:
var a = JSON.stringify(context.instance[0].dataValues)
var b = JSON.stringify(context.instance[2].dataValues)
res.send('{'+JSON.parse(a+','+b)+'}')
Why I receive this error?
"Unexpected token , in JSON at position 53"
At the end I need something like:
{
"idP": 1,
"pasaporteNum": 787643682,
"fidP": 1,
"fid_p": 1
},
{
"idP": 4,
"pasaporteNum": 456789,
"fidP": 2,
"fid_p": 2
}
regards

Seeing as you have two objects with the same properties, you probably just want to add those to an array before stringifying
var arr = [context.instance[0].dataValues, context.instance[2].dataValues]
res.send( JSON.stringify( arr ) )

I think you want to have a JSON format and send from your api, so you need not JSON.parse() but JSON.stringify().
var a = JSON.stringify(context.instance[0].dataValues);
var b = JSON.stringify(context.instance[2].dataValues);
res.send('{' + JSON.stringify(a + ',' + b) + '}');

with your format, you want an array instead of an object .
res.send('['+JSON.parse(a+','+b)+']')
or simpler you can do
JSON.stringify([context.instance[0].dataValues,context.instance[2].dataValues])

You don't need to use .stringify() and .parse(), Just as create an array and send it.
res.send([context.instance[0].dataValues, context.instance[2].dataValues])

Related

Convert JSON String to JSON Object in JavaScript

I understand there are many similar questions exist, however I couldn't find a proper answer.
Consider the Javascript object,
var a = [ { defaultCount:'200' , timeintervals : [{ day:'Weekday', from:'9:00', to:'18:00', count:'100' }, { day:'Weekday', from:'9:00', to:'18:00', count:'100' } ]}];
Now running a[0].defaultCount gives me "200" as expected.
Now the same Javascript object, I am putting inside double quotes.
var b = "[ { defaultCount:'200' , timeintervals : [{ day:'Weekday', from:'9:00', to:'18:00', count:'100' }, { day:'Weekday', from:'9:00', to:'18:00', count:'100' } ]}]";
here b[0] gives me "[" and b[4] gives me "d" so on.
If I understand correctly, var a is JavaScript Object and var b is String.
I am receiving var b from the Java side as a String.
How do I convert var b into a form that I can iterate as I do on var a ?
I have tried :
var c = JSON.parse(b) but getting syntax error.
I really do not wish to change the JSON format much as it is the template used in the Java end as well.
Are there any easy workarounds ?
console screenshot
[{
"defaultCount":"200" ,
"timeintervals": [{ "day":"Weekday", "from":"9:00", "to":"18:00", "count":"100" }, { "day":"Weekday", "from":"9:00","to":"18:00", "count":"100"}]
}]
use double quotes

Custom query parameters format serializer and extractor [JS]

I have a JSON object of the type
[
{
at: "own",
op: "in_between",
va: ["str", "jan"]
},
{
a: 'alas',
op: 'cont',
va: [10, 20]
},
.
.
.
]
I want to pass this as a GET query parameter. Now I could just stringify it and pass it as something like this
?q={"0":{"at":"own","op":"in_between","va":["str","jan"]},"1":{"at":"alas","op":"cont","va":[10,20]}}
However I would prefer to serialize it in a different format. Something like
q[]=at:"own"|op:"in_between"|va:["str","jan"]&q[]=at:"alas"|op:"cont"|va:[10,20]
(I saw a this kind of format being used in Amazon's search filters. Any other format suggestions are welcome. My main goal is to shorten the URL)
So i was able to serialize it by just concatenating to a string
let q = "";
data.forEach(function(i) {
q = q.concat(`q[]=at:"${i.at}"|op:"${i.op}"|va:[${i.val}]&`);
});
return q.slice(0,-1);
Similarly I have an extractor
let qArray = q.split('&');
let qParse = [];
qArray.forEach(function(i) {
i = JSON.parse('{' + i.substring(4).split('|').join(',') + '}');
q.push(i);
});
However this only works well for q[1] where q[1]['va'] has an integer array. It needs to also work for q[0] with the string values
Also is there any better way of serializing and extracting it in these kinds of forms?
Thanks in advance!
As said previously in the comments, I was wondering if CSV wouldn't work for what you want. It's kind of easy to parse. Would this work (assuming filters is your array) ? :
let params = "?q=;at,op,va;";
filters.forEach(function(fil) {
params += fil.at + "," + fil.op + "," + JSON.stringify(fil.va) + ";";
})
If you want to store queries to make percentage, you'd just have to remove first three characters. I'm also supposing that all your dictionnaries follow the same structure. Hope this works for you

How to access JSON-object with multiple values per key?

At the moment I am stuck with a problem that just seems stupid, but I don't know the answer to it.
I am trying to access this JSON-object:
var custom_fields =
{
"28246": 5123,5124,5125
}
I would like to get each value from that key. I would know how to access it if it was a nested-object, but it isn't sadly (it is coming from an API, which I can't change the JSON-response from sadly)
What I tried already is the following:
for (var key in custom_fields) {
if (custom_fields.hasOwnProperty(key)) {
console.log(key + " -> " + custom_fields[key]);
}
}
The problem here is that the result will be like this:
1 -> 5
2 -> 1
3 -> 2
4 -> 3
5 -> ,
6 -> 5
...etc...
Any suggestions are welcome, I am trying to access it in javascript/Jquery.
Thanks for helping in advance!
I assume that the data is in this format (note the string literals):
var custom_fields = {
"28246": "5123,5124,5125"
}
If that is the case, you can use String.split.
In your case, it would be something like this:
const values = custom_fields['28246'].split(',');
The values of they key 28246 are now stored in the new variable values as an array:
['5123','5124','5125']
If you want to parse all values to integers, I suggest using Array.map:
const valuesAsInt = custom_fields['28246'].split(',').map(value => parseInt(value);
Which will lead to this:
[5123, 5124, 5125]
Disclaimer: When using newer ECMAScript features such as Array.map, be sure to either use a browser which supports this our include a polyfill.
You can access it by using split function which will convert it into an array and then get the values from that array as below code.
var data = {
"28246": '5123,5124,5125'
}
var arr = data['28246'].split(',');
$.each(arr, function( index, value ) {
console.log(value);
});
You can split by ',' and transform each element to integer by using array.map and '+' operator:
var custom_fields =
{
"28246": "5123,5124,5125"
}
custom_fields["28246"] = custom_fields["28246"].split(',').map(el => +el);
console.log(custom_fields);
console.log(custom_fields["28246"][0], custom_fields["28246"][1], custom_fields["28246"][2]);

How to push new key/value pair into external json file? [duplicate]

I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
I want to add a new item to the array, such as
{"teamId":"4","status":"pending"}
to end up with
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.
JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.
elementToPush = [1, 2, 3]
if (!obj.arr) this.$set(obj, "arr", [])
obj.arr.push(elementToPush)
(This answer may not be relevant to this particular question, but may help
someone else)
Use spread operator
array1 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Organization"
}
];
array2 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Division"
}
];
array3 = [
{
"column": "Level",
"operator": "=",
"value": "Country"
}
];
console.log(array1.push(...array2,...array3));
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<i class="fa fa-shopping-cart"></i>Add to cart'
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
How do I store a simple cart using localStorage?

How to parse dynamic json data?

I am using wikipedia API my json response looks like,
"{
"query": {
"normalized": [
{
"from": "bitcoin",
"to": "Bitcoin"
}
],
"pages": {
"28249265": {
"pageid": 28249265,
"ns": 0,
"title": "Bitcoin",
"extract": "<p><b>Bitcoin</b>isapeer-to-peerpaymentsystemintroducedasopensourcesoftwarein2009.Thedigitalcurrencycreatedandlikeacentralbank,
andthishasledtheUSTreasurytocallbitcoinadecentralizedcurrency....</p>"
}
}
}
}"
this response is coming inside XMLHTTPObject ( request.responseText )
I am using eval to convert above string into json object as below,
var jsonObject = eval('(' +req.responseText+ ')');
In the response, pages element will have dynamic number for the key-value pair as shown in above example ( "28249265" )
How can I get extract element from above json object if my pageId is different for different results.
Please note, parsing is not actual problem here,
If Parse it , I can acess extract as,
var data = jsonObject.query.pages.28249265.extract;
In above line 28249265 is dynamic, This will be something different for different query
assuming that u want to traverse all keys in "jsonObject.query.pages".
u can extract it like this:
var pages = jsonObject.query.pages;
for (k in pages) { // here k represents the page no i.e. 28249265
var data = pages[k].extract;
// what u wana do with data here
}
or u may first extract all page data in array.
var datas = [];
var pages = jsonObject.query.pages;
for (k in pages) {
datas.push(pages[k].extract);
}
// what u wana do with data array here
you can archive that using two methods
obj = JSON.parse(json)
OR
obj = $.parseJSON(json);
UPDATE
Try this this
var obj = JSON.parse("your json data string");
//console.log(obj)
jQuery.each(obj.query.pages,function(a,val){
// here you can get data dynamically
var data = val.extract;
alert(val.extract);
});
JSBIN Example
JSBIN

Categories

Resources