Regex to wrap JSON property value inside another string. MongoDB transition - javascript

I'm trying to insert some data from a proprietary JSON database into MongoDB for testing purposes. My data is currently in a json file in the format:
{ "_id": "213124123114",
"foo":bar",
"otherId": "2324242424",
...
}
To keep my test data relationships intact, I want to use sed to wrap all the _id and xxxId values with ObjectId(...)
My data would then look like:
{ "_id": ObjectId("213124123114"),
"foo":bar",
"otherId": ObjectId("2324242424"),
...
}
I would then take the data and insert it into mongo in the same format as displayed in the file.
I'm testing my regex in javascript, but the following assignment blows up:
var y = s/"_id":(\s?"[0-9]+"),/ObjectId($1)/gi
SyntaxError: Unexpected token :
Escaping the ':' doesn't seem to do anything.
When I remove the capture flag at the start, the regex assignment works as expected
var y = /"_id":(\s?"[0-9]+"),/
var p = "\"_id\": \"123123123121321212312\",";
y.test(p) === true
but I have no way to capture the value block I need to wrap.
Any ideas what I'm doing wrong?

Try this:
json.replace(/("(?:_id|otherId)": ?)("\d+")/g, '$1ObjectId($2)');
Here's a fiddle: http://jsfiddle.net/7WJBm/1/

Related

Validated JSON throwing SyntaxError: Property must be a string literal

I have a validated JSON that I'm pulling into my app, but as soon as I choose an item related to the JSON the app just goes into a forever "loading" cycle.
The error I receive is Error: Uncaught (in promise): SyntaxError: JSON Parse error: Property name must be a string literal.
Here is my validated JSON:
{
"lodges": [
{
"title": "Lakeside Lodge",
"url_title": "lakeside-lodge",
"lodges_short_name": "Lakeside",
"lodges_description": "<h5><strong>Coming Soon: Estimated Opening Fall 2021 </strong></h5><p>The Lakeside Lodge sits will rest in the center of this premier state park, Lakeside State Park.</p>",
"lodges_summary": "<p>Anticipated opening in Fall 2021, the new 85-room Lodge at Lakeside State Park!</p>",
"reservation_link": "null"
}
]
}
Here is the code I am using to get and display in the data:
showAmenities(item){
let list : any;
let res : any;
switch (item) {
case 'lodges':
this.data.getParkLodges(this.park).then(data => {
let res = JSON.parse(data);
let list = res.lodges;
this.openAmenityListPage(item,list);
}
}
}
openAmenityListPage(item,list){
let amenitiesModal = this.modalCtrl.create(ParkAmenitiesListPage, {title : item, listItems: list, park: this.parkDetails.title, parkShortName: this.parkShortName });
amenitiesModal.present();
}
I am able to get data and display other JSON's that are identical, but for some reason this one is throwing this error.
Edit: I am working with other APIs with HTML tags within their values, and those are working perfectly fine.
Your JSON string contains escaped double quotes: <a href=\"/parks/lakeside\">.
The escaping "gets lost" as soon as the JSON code is interpreted as a string by Javascript. Escaped quotes in a string become normal quotes:
console.log('a text with \"quotes\".') // --> logs 'a text with "quotes"'.
So in your case, the actual string that JSON.parse() sees, and that leads to a parse error, is like:
'{ "lodges_description": "<a href="/parks/lakeside">" }, ...'
You need to escape the escape character, so that Javascript knows you want to pass the actual backslash character to the JSON.parse() function:
console.log('a text with \\"quotes\\".') // --> logs 'a text with \"quotes\"'.
Turns out there was a relationship API with a channel I was working with that contained an extra comma. :D
This question is closed.

Unable to parse JSON data properly in JQuery

This is my first time to convert JSON data with jQuery however, I get the following error when I try to convert the JSON string. Am I doing something wrong? I was searching for some simple sites about converting JSON string in jQuery, but most of the tutorial seems a bit difficult to understand. I would love to here some tips about converting jsons from url with jQuery if possible.
var obj = jQuery.parseJSON( '{"result":[{"id":"25","name":"loplo\n","score":"1198"},{"id":"58","name":"adjm","score":"1131"},{"id":"60","name":"dragon with ","score":"1083"},{"id":"57","name":"tDj","score":"799"},{"id":"59","name":"dragon with ","score":"452"},{"id":"55","name":"Donny","score":"450"},{"id":"56","name":"ajo ","score":"401"},{"id":"61","name":"make ","score":"392"}]}' );
Error message
Uncaught SyntaxError: Unexpected token
in JSON at position 35
at JSON.parse (<anonymous>)
at Function.m.parseJSON (jquery-1.11.1.min.js:4)
at leaderboard.js:16
The reason you're getting that error message is the \n in the first element that has the name: "loplo\n"
This is because new lines are allowed in JSON objects like that as they need to be either removed or escaped.
To get around this you can do
var obj = jQuery.parseJSON(mystring.replace(/\n/g,"\\n"));
You can read more about this here:https://bugs.chromium.org/p/v8/issues/detail?id=616
This is because you have the new line character as the value of loplo:
"loplo\n"
Remove the \n and it should work.
I don't recommend removing all of the \n with replace because you may want that. If you want to keep the \n, add a escape character before it, like this:
"loplo\\n" and it should work.
use this...
var e = '{"result":[{"id":"1351","identite":"RES ADDS","etat":"1","email":"udohou#gmail.com","telephone":"8787878","adresse":"COTONOU","nom_pays":"Togo","indicatif":"228"},{"id":"1350","identite":"MY DREAM","etat":"2","email":"dohouulrich#gmail.com","telephone":"5248525","adresse":"COTONOU","nom_pays":"Togo","indicatif":"228"},{"id":"1349","identite":"UN ","etat":"1","email":"dohouulrich#gmail.com","telephone":"66353364","adresse":"","nom_pays":"Benin","indicatif":"229"},{"id":"1348","identite":"DOHOU ULRICH SEMASSA & Fils","etat":"1","email":"dohouulrich#gmail.com","telephone":"66353364","adresse":"COTONOU","nom_pays":"Benin","indicatif":"229"},{"id":"1344","identite":"DC","etat":"2","email":"dohouulrich#gmail.com","telephone":"66353364","adresse":"","nom_pays":"Afghanistan","indicatif":"93"},{"id":"1343","identite":"AGAIN","etat":"2","email":"dohouulrich#gmail.com","telephone":"66353364","adresse":"","nom_pays":"Afghanistan","indicatif":"93"},{"id":"1342","identite":"SOCIAL LIMITED","etat":"3","email":"dohouulrich#gmail.com","telephone":"66353364","adresse":"","nom_pays":"Afghanistan","indicatif":"93"}]}';
var json = JSON.stringify(eval('(' + e + ')'));
var arr = $.parseJSON(json);
var resultData = arr['result'] ;
console.log(resultData) ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I changed the Json String data because yours was not working. I think it is not well formated

Json in Python with a var giving error

I have this javascript file which looks like below:
var abc= {
"a" : {
"label": "Monthly",
"URL": "xyz.com",
"ArchTag": "M",
"archData": {
"Feb 2016":"20160229",
"Jan 2016":"20160129",
"Dec 2015":"20151231"
}}};
so I want a way to edit this and say add a new month detail. I guess its a json inside javascript. So how can one edit it in a standard way.
If you can rely on the data looking exactly like this every time then you can just hack off the bit that stops it being JSON:
json_data = json.loads('{' + json_file.read().partition('{')[2])
(or use a regex, or whatever you prefer for string manipulation)
You should still beware that JavaScript is not the same as JSON, so you need some confidence that what you're given will always be an assignment of a valid JSON associative array to a variable.
If, on the other hand, you're being passed arbitrary JavaScript and you're expected to evaluate it, then you have a much bigger problem to solve. What if someone gives you var xyz = "Monthly"; var abc = {"label" : xyz, "URL" : "xyz" + "." + "com"}?
You need a JavaScript engine to solve that more general problem, not just a JSON parser. For example, js2py claims to be a complete JavaScript engine written in Python, but I've never used it so I can't recommend or dis-recommend it.
There are also security issues to consider in executing code from untrusted sources, beyond those you consider if all you're doing is parsing JSON from an untrusted source. So if you need to use a JavaScript engine, make sure you properly understand how it is sandboxed.
Your code is Javascript, not JSON...
With this code in JS you just create a new Object.
But JSON IS NOT A LANGUAGE!!.!
Json is a solution to efficiency store/transmit datas (as assiocative arrays).
Just try to do not define abc:
Your JSON file:
{
"a" :
{
"label": "Monthly",
"URL": "xyz.com",
"ArchTag": "M",
"archData":
{
"Feb 2016":"20160229",
"Jan 2016":"20160129",
"Dec 2015":"20151231"
}
}
}
If you can not remove var abc of your file, read the file in a string, remove the first characters of the string and load the new string.
try:
with open(file) as json_file:
data = file.read()
json_data = json.loads(data[9:])
pprint(json_data)
except Exception as e:
print(e)
if it is not always written var abc then start your string at the first { index.
Actually the file content is not json because of the var you mentioned. you should remove that part dynamically:
json_text = json_file.read().replace('var abc=','')
json_data = json.dumps(json_text)
pprint(json_data)
You can use regex to replace the var assignment piece:
with open('file.txt') as json_file:
data = json_file.read()
data = re.sub(r'^var\s*\S*\s*=\s*', '', data)
json_data = json.loads(data)

SyntaxError: JSON Parse error: Unexpected EOF

I have the following line of code:
data = jQuery.parseJSON(data);
Which is creating the following error...
SyntaxError: JSON Parse error: Unexpected EOF
I can't work out how to identify what's causing the error though.
Any ideas?
Here's the data...
{
"element_type": "paint",
"edit_element_id": "2117",
"paint_id": "15",
"paint_editable_data": "zwibbler3.[{\"id\":0,\"type\":\"GroupNode\",\"fillStyle\":\"#cccccc\",\"strokeStyle\":\"#000000\",\"lineWidth\":2,\"shadow\":false,\"matrix\":[1,0,0,1,0,0],\"layer\":\"default\"},{\"id\":1,\"type\":\"PageNode\",\"parent\":0,\"fillStyle\":\"#cccccc\",\"strokeStyle\":\"#000000\",\"lineWidth\":2,\"shadow\":false,\"matrix\":[1,0,0,1,0,0],\"layer\":\"default\"},{\"id\":2,\"type\":\"BrushNode\",\"parent\":1,\"fillStyle\":\"#cccccc\",\"strokeStyle\":\"#000000\",\"lineWidth\":10,\"shadow\":false,\"matrix\":[1,0,0,1,0,0],\"layer\":\"default\",\"points\":[17,21,17,22,17,24,17,28,18,34,37,55,49,59,70,61,89,56,92,55,93,54]},{\"id\":3,\"type\":\"PathNode\",\"parent\":1,\"fillStyle\":\"#e0e0e0\",\"strokeStyle\":\"#000000\",\"lineWidth\":2,\"shadow\":false,\"matrix\":[1,0,0,1,-14,-85],\"layer\":\"default\",\"textFillStyle\":\"#000000\",\"fontName\":\"Arial\",\"fontSize\":20,\"dashes\":\"\",\"smoothness\":0.3,\"sloppiness\":0,\"closed\":true,\"arrowSize\":0,\"arrowStyle\":\"simple\",\"doubleArrow\":false,\"text\":\"\",\"roundRadius\":0,\"commands\":[0,150,100,6,200,150,200,100,6,150,200,200,200,6,100,150,100,200,6,150,100,100,100,7],\"seed\":36934}]",
"paint_image_data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALwAAAB1CAYAAAD0rovXAAASHklEQVR4Ae1dCXBW1RW+BAKJNAwihMWgkYkN+1JgRGAEBKQtISIVcBoQRGiKhBadQXQ07XQoVhwQtLiwVGSzUEAgwGgAIVgMyCbLsAlllzVSFSmLhPT7Hv/LvCwk77285V/Omfly33Lfued+9+T+d3v3KSUiDAgDwoAwIAwIA8KAMCAMCAPCgDAgDAgDwoAwIAwIA8KAMCAMCAPCgDAgDAgDwoAwIAwIA8KAMCAMCAPCgDAgDAgDwkA4M1ApnDMneSuTgXtwt34A9QzH+jU9pJKzpeBcsWvfMmKwizh8sJeQc/YlQ1VXoFsgrIvQSTkPZT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GjRIpaenB63j09G5b8z8+fP1SSSOSM0FMgE23VwXcXjXKXY9gWZIgY7/BFOKiYlRqampavDgwapFixa85Lvs3btXzZs3T2VlZenbaNAmvqFER9/HE69EHN4rpt1PpzWSeBXoB2jlmpSUpHr16qWhZcuW7ltgSIHLAbhEgjB8SY9Di5xj+CtgeeGXQb3tQ3F429QF7YPc/2YE8AxQR7eS7fsOHTpoE1gMGzXS+r367QqHHD/fsmWLys3N1UI2XwzCV/A48jITOGK47vmhOLznlHuWYDRSegTgMlriPqBQ2Obn4rT4+HgtLH6sn/OBCxcuKG5jp8N4rh8HFnYV6sfBSWBFAJ8j5AZJvos4vO9F4JkBXJDTFegWCJ1einkeenMC2IAwKDfEF4dHyUSo3IN81w+gnuFYv6aHpOdsKThX7BrfQBIRBoSBYGLg/9jYtJnVySp3AAAAAElFTkSuQmCC"
}
Is it the size that's the problem maybe?
It looks like you are trying to convert a text string into a JSON data object.
You should probably be doing the following:
instead of using jQuery.parseJSON(data), rather just use JSON.parse(data).
The error you mentioned indicates you are passing in an empty string "" as your value of data. So check the value that is being passed in to the parse method.
The data object you mentioned that you are passing in will always result in an error since it's already in a JSON format.
The parse method is intended to do the following conversion.
JSON.parse("{\"hello\":\"world\"}") returns {hello:'world'}
If you are trying to convert in an object into a string, you can try this:
JSON.stringify({hello:'world'}) returns "{\"hello\":\"world\"}"
The reason is simple. When you define the JSON in the script, the double quotes should be represented by \" , not " .
In my case i was also facing that same error in React-native but after look into my code i found that .. .my API hit URL was not complete .. and after that.. my problem was resolved :)
Maybe you can do with the eval method :
if (data !== null) {
var json_obj= eval("("+data+")"); //jQuery.parseJSON(data);
//just for check the the keys
var keys = Object.keys(json_obj);
for (var i = 0; i < keys.length; i++) {
console.log(keys[i]);
};
}

putting json into javascript variable

I want to put a JSON object into a javascript variable as a sting in order to create a graph.
qm.createGraphData = function() {
$.post("ajax_getGraphDataWebsite ", function(json) {
qm.negativesData = json;
},"json");
qm.data = [{
"xScale":"ordinal",
"comp":[],
"main":[{
"className":".main.l1",
qm.negativesData},{
"className":".main.l2",
qm.negativesData}],
"type":"line-dotted",
"yScale":"linear"}];
}
the string value should be added to the "data" section. Now the object get's added but I need to add the string value to the variable like the sample below:
{"data":[{"x":"3283581","y":"2013-10-16"},{"x":"1512116","y":"2013-10-17"},{"x":"3967","y":"2013-10-18"},{"x":"1094","y":"2013-10-19"},{"x":"853","y":"2013-10-20"},{"x":"1205","y":"2013-10-21"},{"x":"2618700","y":"2013-10-22"},{"x":"3928291","y":"2013-10-23"},{"x":"3670318","y":"2013-10-24"},{"x":"3347369","y":"2013-10-25"},{"x":"2525573","y":"2013-10-26"},{"x":"3224612","y":"2013-10-27"},{"x":"3992964","y":"2013-10-28"},{"x":"3949904","y":"2013-10-29"},{"x":"3568618","y":"2013-10-30"},{"x":"3104696","y":"2013-10-31"},{"x":"3246932","y":"2013-11-01"},{"x":"2817758","y":"2013-11-02"},{"x":"3198856","y":"2013-11-03"},{"x":"3952957","y":"2013-11-04"},{"x":"3934173","y":"2013-11-05"},{"x":"3878718","y":"2013-11-06"},{"x":"3642822","y":"2013-11-07"},{"x":"3186096","y":"2013-11-08"}]}
This would generate the right graph for me. Does anyone know how to convert the json object into a string like above and to send it to the qm.negativesData variable?
// UPDATE
Now I've got the string with the qm.negativesData = JSON.stringify(json); solution
But my qm.negativesdata won't get added to the qm.data variable... i'm getting a console error SyntaxError: invalid property id
I suppose i'm not adding them the right way?
To convert a JSON object into a JSON string, you can try myObject.stringify(), JSON.stringify(myObject), or if you are using a library using the built in function of that library.
So, you could do something like: qm.negativesData = myObject.stringify()
Cheers

Categories