Convert String to Array of JSON Objects (Node.js) - javascript

I'm using Node.js and express (3.x). I have to provide an API for a mac client and from a post request I extract the correct fields. (The use of request.param is mandatory) But the fields should be composed back together to JSON, instead of strings.
I got:
var obj = {
"title": request.param('title'),
"thumb": request.param('thumb'),
"items": request.param('items')
};
and request.param('items') contains an array of object but still as a string:
'[{"name":"this"},{"name":"that"}]'
I want to append it so it becomes:
var obj = {
"title": request.param('title'),
"thumb": request.param('thumb'),
"items": [{"name":"this"},{"name":"that"}]
};
Instead of
var obj = {
"title": request.param('title'),
"thumb": request.param('thumb'),
"items": "[{\"name\":\"this\"},{\"name\":\"that\"}]"
};
Anyone who can help me with this? JSON.parse doesn't parse an array of object, only valid JSON.

How about this:
var obj = JSON.parse("{\"items\":" + request.param('items') + "}");
obj.title = request.param('title');
obj.thumb = request.param('thumb');
JSON.stringify(obj);

Perhaps I'm missing something, but this works just fine:
> a = '[{"name":"this"},{"name":"that"}]';
'[{"name":"this"},{"name":"that"}]'
> JSON.parse(a)
[ { name: 'this' }, { name: 'that' } ]
Node#0.10.13

May be you have old library Prototype. As I remove it, bug has disappeared.
You can try the same code. Once in page with Prototype.js. Second time in new page without library.

Related

How to repalce HTML text with JSON data

Received data from api and converted into JSON format, however every time I try to change a selected element in HTML I get either undefined or Object Obejct.
I have tried JSON.parse/JSON.stringify. I have tried innerHTML, innerText, textContent. I have tried for loops.
HTML
<p id="lang">C++</p>
Javascript
let language = document.getElementById('lang');
let data = {
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
}
]
};
data = JSON.stringify(data);
language.innerHTML = data.book.language;
Need C++ in paragraph tag to change to Java in data. If Jquery would make this easier I would appreciate knowing how that works as well.
Since the data model you presented has books as an array, you'll need to get that out this way
data.book[0].language
0 being the index of whatever book you want to display
data = {
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
}
]
};
language.innerHTML = data.book[0].language;
This is not working as book is an array of objects, not a singular object. So you'd need to use data.book[0].language
P.S. You don't need to use JSON.stringify here, if you are receveing a JSON string from your API, you should use JSON.parse
Here is an example of the code running correctly:
https://jsfiddle.net/2et3zh7g/
From Mozilla
The JSON.stringify() method converts a JavaScript object or value to a JSON string
So it seems your code is going the opposite direction of your stated intent.
let data = {
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
}
]
};
After which, data already contains an object.
data = JSON.stringify(data);
And now, data contains a string. So naturally, data.book will result in an undefined value.
If, however, you were to receive the data as actual JSON, such as
let dataJSON = '{"book":[{"id":"01","language":"Java","edition":"third","author":"Herbert Schildt"}]}';
You could then extract the language value using JSON.parse as follows:
let data = JSON.parse(dataJSON);
let bookLanguage = data.book[0].language;
language.innerText = bookLanguage;
Note the array subscript on book. Since in your example, it contains an array of objects, you need to be sure to subscript into it.

How to unescape json.stringify output inside a object array

I'm getting a bad response when i post a json.stringify via fetch, and the problem is from escaped quotes that json.stringify is producing. It works when I remove them manually, but I need this to be done automatically.
var order = {
"from_country": "US",
"line_items": [
{
"quantity": 1,
"unit_price": 19.95
}
],
"to_country": "US"
};
var body = JSON.stringify(order);
var body will display as:
{"from_country":"US","line_items":"[{\"quantity\": 1, \"unit_price\": 19.95}]","to_country":"US"}
I'd like it to display as:
{"from_country":"US","line_items":"[{"quantity": 1, "unit_price": 19.95}]","to_country":"US"}
The issue was that my file includes the prototype library.
I fixed the conflict, while still maintaining the functionality(I think) of prototype by adding this code -
JSON = JSON || {};
JSON.stringify = function(value) { return Object.toJSON(value); };
JSON.parse = JSON.parse || function(jsonsring) { return jsonsring.evalJSON(true); };
I first stumbled on this being the problem here:https://stackoverflow.com/a/20331694/8326722
which led me to https://stackoverflow.com/a/1327371/8326722 and then I added the bit from a comment to get it to work with objects.
If someone can explain how the code I'm using works, that would be nice.

Adding a new array element to a JSON object

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?

JavaScript parsing a JSON file

I am using the following code to parse a single line of a JSON file:
var str = '{ "jobID": "2598752", "account": "TG-CCR120014", "user": "charngda",
"pkgT": {"mvapich2-new/1.2": { "libA": ["libmpich.so.1.1"], "flavor": ["default:pgi/7.2-5"] } },
"startEpoch": "1338608868", "runTime": "48", "execType": "user:binary", "exec": "IOR",
"numNodes": "4", "sha1": "755187bd8550881bb0c9951822e74a9a53c8d0f3", "execEpoch": 1336757832,
"execModify": "Fr, Ma, 1, 12:37:1, 2012", "startTime": "Fr, Ju, , 22:47:4, 2012",
"numCores": "64","sizeT": { "bss": "36224", "text": "3502656", "data": "128944" } }';
var obj = JSON.parse(str);
delete obj['flavor'];
delete obj['pkgT'];
var newstr = JSON.stringify(obj);
document.write(str);
However, I want to parse the entire 6000 line JSON file. How do i read the file line by line and delete the fields as I have done with the single line. I have zero experience with Javascript so I have no clue how to read a file or create a new file. I assume I would use some sort of array, but I am not sure. Can anyone help?
If your file looks like this:
[{"jobID": "1",...},{"jobID": "2",...},{"jobID": "3",...},...]
You can do something like this:
var objArray = JSON.parse(str);
for( var k=0; k<objArray.length; k++ ) {
delete objArray[k]['flavor'];
delete objArray[k]['pkgT'];
}
var newstr = JSON.stringify(objArray);
document.write(newstr);
Just add the complete file content to the str variable by copy and paste.
This solution won't help you if you need to do this on a regular basis !
Something like this will probably work. I haven't got a 6000 line JSON file to test it on, but it should at the least give you a clear idea where you should be going next with your solution.
Remember, JSON blocks are just ordinary javascript objects which are a data structure already with their own methods, so you can iterate over them by just using standard object iteration.
var bigObj = json.parse(jsonFile);
var objArray = [];
var newStr;
for (var obj in bigObj){
if (bigObj.hasOwnProperty(obj)){
delete obj['flavor'];
delete obj['pkgT'];
newStr = JSON.stringify(obj);
objArray.push(newStr);
}
}
document.write(objArray.join("/n").toString());

JavaScript JSON parse by a given key without looping

Given a JSON string as this:
{
"__ENTITIES": [
{
"__KEY": "196",
"__STAMP": 1,
"ID": 196,
"firstName": "a",
"middleName": "b",
"lastName": "c",
"ContactType": {},
"addressCollection": {
"__deferred": {
"uri": "/rest/Contact(196)/addressCollection?$expand=addressCollection"
}
},
"__ERROR": [
{
"message": "Cannot save related entity of attribute \"ContactType\" for the entity of datastore class \"Contact\"",
"componentSignature": "dbmg",
"errCode": 1537
}
]
}
]
}
Is there a method to get just the __ERROR record, I know I can use
var mydata = json.parse(mydata) and then find it from the mydata object. But I was hoping there was a method to only return the ERROR field something like
json.parse(mydata, "__ERROR") and that gets only the information in the __ERROR field without turning the whole JSON string into an object
"Is there a method to get just the __ERROR record, I know I can use var mydata = json.parse(mydata) ... But I was hoping there was ... something like json.parse(mydata, "__ERROR")"
There may be libraries that do this, but nothing built in. You need to write code that targets the data you want.
The closest you'll get will be to pass a reviver function to JSON.parse.
var errors = [];
var mydata = JSON.parse(mydata, function(key, val) {
if (key === "__ERROR")
errors.push(val);
return val
});
without turning the whole json string into an object
That's hardly possible, you would need some kind of lazy evaluation for that which is not suitable with JS. Also, you would need to write your own parser for that which would be reasonable slower than native JSON.parse.
Is there a method to get just the __ERROR record
Not that I know. Also, this is an unusual task to walk the whole object tree looking for the first property with that name. Better access __ENTITIES[0].__ERROR[0] explicitly.
If such a function existed, it would have to parse the whole thing anyway, to find the key you're looking for.
Just parse it first, then get the key you want:
var mydata = JSON.parse(mydata);
var errorObj = mydata.__ENTITIES[0].__ERROR[0];
If you want, you may create your own function:
function parseAndExtract(json, key) {
var parsed = JSON.parse(json);
return parsed[key];
}

Categories