Mapping values between JSON arrays - javascript

I seem to have run into a rather unusual problem. Using a form builder I am able to store and render an admin created form in JSON format like so:
EDIT: this is my pulled data from MongoDB hence the id, i directly push my generated JSON into Mongo, i eliminate the ID part on fetching the data.
{
"_id" : ObjectId("5985608427f8510788b468ab"),
"fdata" : [
{
"type" : "header",
"subtype" : "h1",
"label" : "Date Of Commencement"
},
{
"type" : "paragraph",
"subtype" : "p",
"label" : "The partnership business shall be deemed to have commenced on and from <div><br></div>"
},
{
"type" : "date",
"required" : true,
"label" : "Date Field",
"description" : "Date Of Commencement",
"className" : "form-control",
"name" : "date-1501913203863"
}
]
}
Once it is rendered and values are filled in by a user i receive the values at the back end like so: (NODEJS)
{"date-1501913203863":"2017-08-12"}
Now I have to render the form back but with the filled values and it should look like a filled form. Is there a native way in JSON to do this? I was planning to go ahead with a python script to match the values to the fields but that seemed like overkill for this problem.
I hope to get some advise on this topic and not code. Your help is greatly appreciated!

Related

node.js correct extending of json objects

I'm currently using node-ews in a project to access an Exchange Web Server via node.js. Now i ran into a weird problem. To run for example a "CreateItem" request, which can be an E-Mail or Appointment for example, I'm giving the function the arguments as a json similar to this
var args = {
"attributes" : {
"SendMeetingInvitations" : "SendToAllAndSaveCopy"
},
"SavedItemFolderId": {
"DistinguishedFolderId": {
"attributes": {
"Id": "calendar"
}
}
},
"Items" : {
"CalendarItem" : {
"Subject" : "",
"Body" : {
"attributes" : {
},
"$value" : ""
},
"ReminderIsSet" : "true",
"ReminderMinutesBeforeStart" : "30",
"Start" : "",
"End" : "",
"IsAllDayEvent" : "false",
"LegacyFreeBusyStatus" : "Busy",
"Location" : ""
}
}
};
As the REST-API I'm writing will receive Attributes like Subject, Start, End etc. I initially stripped out those out of the JSON and would define them later like
args.Items.CalendarItem.Subject = req.body.Subject;
Oddly this will make the internal validation of node-ews fail and tell me that CalendarItem has an invalid Child Subject. If i leave Subject als an empty string in the initial args and later change it set it to req.body.Subject it works just fine.
My question is this: Is the Object somewhat different if I later add attributes and if yes is there a way to do it right? Because I don't think its the best way to have a bunch of empty Attributes in my Object if they aren't used and define standard values for all of them even if api won't require them to be sent.
Would great if someone knew the answer. Hope i could clarify what the problem is
Ok,
so the problem seems to be this. Internally the JSON "object" seems to have an order based on the order the variable is defined. in JavaScript this is no problem. But when the xml is parsed, the tag that was defined last will also be at the end of the xml so if you had
<someTag>
<variable2 />
<variable3 />
</someTag>
and you add variable1 to your json by someTag.variable1 = x in the end the xml will look like this after beeing parsed by node-ews
<someTag>
<variable2 />
<variable3 />
<variable1 >x</variable1>
</someTag>
Now unfortunately the exchange web server seems to be picky about the order of the xml tags. so when you build your json be sure to use the direct order. Changing content of the json later will not affect the order.

Using JSON in ColdFusion application

I have a website that has a front-end view for non-registered users and then a portal view for registered users.
I am trying to re-vamp the product navigation, wanting to make it easily maintainable for adding/removing links I want this to be in JSON format.
I am using Mura CMS with ColdFusion.
Probably a fairly simple thing I am trying to do but cannot find any examples online.
I have my JSON data as below:
{
"category" : [
{
"name" : "digital stickers",
"products" : [
{
"name" : "round digital stickers",
"urlPublic" : "index.cfm/digital-stickers/round-stickers",
"urlPortal" : "tab=round digital stickers"
},
{
"name" : "square digital stickers",
"urlPublic" : "index.cfm/digital-stickers/square-stickers",
"urlPortal" : "tab=square digital stickers"
}
]
},
{
"name" : "Litho stickers",
"products" : [
{
"name" : "round litho stickers",
"urlPublic" : "index.cfm/litho-stickers/round-stickers",
"urlPortal" : "tab=round litho stickers"
},
{
"name" : "square litho stickers",
"urlPublic" : "index.cfm/litho-stickers/square-stickers",
"urlPortal" : "tab=square litho stickers"
}
]
}
]
}
As you can see I have the category name, which I will use to determine the 'Digital Stickers' and 'Litho Stickers'. I will then loop through the data to pull out the different products names and depending if portal user or public user will take the data to insert into the URL.
To get started I just need to know how to link this into my ColdFusion application. Not a massive ColdFusion Guru yet, more into my JavaScript languages, so any help here would be highly appreciated.
From there I should be good to go.
Just in case that is a bit vague, like html documents link the stylesheet with a tag - how do you link the JSON to the ColdFusion document? Is it like including a ?
After searching around for a while I found a good example on the help.adobe website.
This line of code accesses the JSON data and pulls it in for use
<!--- Get the JSON Feed --->
<cfhttp url="http://localhost:8500/project/JSON_FILE.json">
After that I Deserialized it with
<cfset cfData=DeserializeJSON(theData)>
Then to test I had everything coming back correctly I used a cfdump
<cfdump var="#theData#">
I wanted to spit out only specific data so I did a cfloop to loop through the data array
<h2>Categories</h2>
<cfloop array="#dataArray#" index="elem">
<!--- print out value for demo purposes --->
<cfoutput>
<h3>#elem.name#</h3>
</cfoutput>
</cfloop>
This printed out 'Digital Stickers' and 'Litho Stickers' as expected.
My resources were Adobe Help - getting and deserializing the JSON and Experts Exchange - Loop over deserialized JSON.

SQL database to Json array

Hello I recently created a database using this tutorial: https://www.digitalocean.com/community/tutorials/a-basic-mysql-tutorial
I need to convert my sql database to a json array (like the one shown below) I am making my first mobile app using phone gap, this question isn't about phone gap but i doubt providing some context can't hurt.
I want the app (which can only use html, css and js) to make requests to a sql database the best way to do this for me is to convert the whole database to a json array once a phone makes one request for the json the new json database will be cached on the phone for that day.
(even if caching like this isn't possible or practical it doesn't matter in regards to this question)
I have added three "listings" to the database with via the following method:
INSERT INTO anime
(id
,category
,genre
,title
,description
,image_link
,date_added
) VALUES
(NULL
,"Mainstream"
,"Action"
,"the title"
,"the name"
,"200 word description"
,"imagename.png"
,'2012-04-14'
);
I am unsure whether this method has created the database the way I wanted, as I have tried making multiple requests for the full information and only one way has worked that being said my PHP skills are rubbish.
I was hoping to generate something along the lines of this (any better ways to format it would be greatly appreciated and how to grab and use information from it easily ) i have been looking at json_encode(); and have read: How to build a JSON array from mysql database and other stacks..
categories: [
{
"category-name" : "Mainstream",
"category-description" : "Everyones watching them for a reason",
"category-link" : "#mainstream",
"Mainstream" : [
{
"genres" : [
{
"genre-name" : "Action",
"genre-description" : "Mainstream: Fight them off",
"list" : [
{
"img" : "www.ActionimglinkMainstream1.com",
"name" : "ActionMainstreamname1",
"description" : "this Action is Mainstream name 1"
},
{
"img" : "www.ActionimglinkMainstream2.com",
"name" : "ActionNewname2",
"description" : "this Action is Mainstream name 2"
},
{
"img" : "www.FantasyimglinkMainstream3.com",
"name" : "FantasyMainstreamname3",
"description" : "this Action is Mainstream name 3"
}
]
},
{
"genre-name" : "Fantasy",
"genre-description" : "Mainstream: I put a spell on you",
"list" : [
{
"img" : "www.FantasyimglinkMainstream1.com",
"name" : "FantasyMainstreamname1",
"description" : "this Fantasy is Mainstream name 1"
},
{
"img" : "www.ActionimglinkMainstream2.com",
"name" : "FantasyNewname2",
"description" : "this Fantasy is Mainstream name 2"
},
{
"img" : "www.FantasyimglinkMainstream3.com",
"name" : "FantasyMainstreamname3",
"description" : "this Fantasy is Mainstream name 3"
}
]
}
]
}
]
}]
Thanks for your time, information and insight! please understand I am new to PHP, mysql and JavaScript but not google/stackoverflow I have googled and searched and tried to do this myself but it's just not working..
Just to be clear I want to know how to covert a mySQL database to a json array that I can make requests to from a html + js mobile app.
To confirm how the database was set up:
I recommend to put answers (right or wrong, doesn't matter, the vote will determine it) into the answer section. Because it is easier to read
Anyway, try this. This is using PDO (an alternative to mysqli)
Connect to database and do a SELECT you can make it as complicated as you want with INNER JOINS, LEFT JOINS, UNIONS, etc
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM anime");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
Then you want to convert it to JSON, via json_encode which you already know
$output = json_encode($result)
You want to output it (as a JSON). You can use echo and don't forget to set the header to be JSON
header('Content-Type: application/json');
echo (output);
Note that this PHP returns you the JSON, and not injecting it into javascript as what #user1871802 suggested

elasticsearch completion field not deleting

I have a simple user info document which includes a completion field.
Mapping:
"properties" : {
"fname" : { "type" : "string" },
"lname" : { "type" : "string" },
"dob" : { "type" : "string" },
"sex" : { "type" : "string" },
"autocomplete" : {
"type" : "completion"
}
}
This is an example of my document.
"person" : {
"sex" : "Male",
"dob" : "11/11/2014",
"fname" : "Julie",
"lname" : "Thomas",
"autocomplete" : "Julie Thomas"
}
The complete suggestion query works perfectly fine. But when I delete this document, the complete suggestion still exist for "Julie Thomas" when I expect this to be deleted as well.
Any suggestion on what I am doing incorrectly?
Thanks!
I am having this problem too. According to the ElasticSearch documentation, completion suggestions need to be expunged from the index using the Optimize command. This is what they say at the bottom of the Completion Suggester Docs.
The suggest data structure might not reflect deletes on documents
immediately. You may need to do an Optimize for that. You can call
optimize with the only_expunge_deletes=true to only cater for deletes
or alternatively call a Merge operation.
... that said. I did this:
curl -XPOST 'http://server:9200/attribute/_optimize?pretty' -d '{
"only_expunge_deletes": true
}'
and the deleted doc still shows up in the completion suggester, even though it does not show up in queries or filters.
... Sorry. Not much of an answer... It's supposed to be the answer, but it might not work for you, just as it's not working for me.
We might have to move to Index-Time Search, which uses a 1-character ngram and do a normal _search query.
Adding an id field to the data, and then refrencing that id field for delete and update, works for us
"index":{"_index":"esIndex","_type":"document","_id":"23d68f060118fbeee699d14eff044a1f"}}
{"text":"vision zero","id":"23d68f060118fbeee699d14eff044a1f","suggest":{"input":"vision zero","payload":{"entity_id":"23d68f060118fbeee699d14eff044a1f"}},"type":"Content"}
Something like the above bulk query data, notice the id field in the data. If we don't put it, we face same issue that after deleting document, it still show up in suggestions.

Nested Maps in JQuery ajax data to send - how to serialize 'properly'?

var location = { "location" : {
"name" : $("#user_loc_name").val(),
"street_address" : $("#user_loc_street_address").val(),
"city" : $("#user_loc_city").val(),
"province" : $("#user_loc_province").val(),
"country" : $("#user_loc_country").val(),
"postal_code" : $("user_loc_postal_code").val(),
"public" : $("#user_loc_public").attr('checked')
}};
( ... )
$.post(url, location, success_callback);
The reason I need this 'nested' map is because I'm sending this to my rails backend, and I'm hoping I can make a simple update _ attributes(params[:location]) in the controller. Unfortunately, with this solution I get Parameters:
{"location"=>"[object Object]", ...}
Not what I'm hoping for. I'm hoping for:
{"location"=> {"name" => "valforname", "street_address" => "valforstreetadress", ...}, <other params>...}
If I get rid of the 'nesting' and just send the inner map it works fine, but each attribute shows up separately in the params hash and it's just cumbersome and messy. If I could get the whole map nested under a key of "location" it would be much nicer.
Have a look at this:
Serializing Objects in Javascript
jQuery does not support JSON serializing OOTB. Try any number of libraries. Here's the standard one:
<script src="http://www.json.org/json2.js"></script>
Your code then looks like:
$.post(url, JSON.stringify(location), success_callback);

Categories