phonegap read and write json file - javascript

I am looking to store a JSON file locally on IOS/Android in a Phonegap(Cordova) application.
Basically, I retrieve a JSON file from the server ($.GETJSON) and I want to first store the JSON file and then retrieve and modify it.
I've looked at FileWriter but I don't see a mimetype... the only example gives text files.
Thanks in advance!
Nick

Nick, just use FileWriter.write to save your JSON data to disk. JSON is a text based file anyway so there is no need to set the mime type. When you are ready to load the file again use FileReader.readAsText. In your "onloadend" handler of the FileReader the method will be called with an event and event.target.result will be your JSON data. Then you'll do a
var myJson = JSON.parse(event.target.result);
to turn the text into a JSON object.

(for template or default settings) I just store them in seperate constant files so i don't have to use any special file utility addons or commands, super easy:
(function(){
angular.module('app').constant('settings_json',
{
"name":"settings",
"data":[
{
"set":"globals",
"share_diagnostics":true,
"user_prefs_save_cloud": true
},
{
"set":"user",
"fname":'',
"lname": '',
"telephone": '',
"email": ''
}
]
}
)})();
Then in your app: (after injecting 'settings_json')
var settings = angular.fromJson(settings_json);

Related

Getting a file URL from Sanity out of a blocks array

I'm building a website using Next JS and Sanity for the CMS. Sanity has built-in schemas for images but not for video, so a video needs to be uploaded with the File schema. The docs suggest that to get a file URL to be used on the front-end you should use the query language GROQ to make this conversion at the request like so:
// GROQ query
*[_type == 'movie'] {
title,
"manuscriptURL": manuscript.asset->url
}
But since I am using the File schema to embed short auto-looping videos into rich text content using the Blocks schema, I don't have the luxury of converting URLs at the request and need to do it dynamically as the blocks array data is being parsed for the #portabletext/react component.
Basically, what I get back for the file is simply an asset reference with the following data:
{
"_type": "file",
"asset": {
"_ref": "file-e4e61f3b231cca8e3339e96e050aee428009c777-gif",
"_type": "reference"
}
}
When I then use Sanity's own #sanity/asset-utils package to get a file URL using their buildFileUrl() function, I get a URL that is undefined for that asset where PROJECT_ID and DATASET are the correct values:
https://cdn.sanity.io/files/[PROJECT_ID]/[DATASET]/undefined.undefined
Here is the function I made, using their package's file URL function, to get the asset URL, which returns the URL above with the undefined values:
export function getSanityFileUrl(sanityFile) {
const fileUrl = buildFileUrl(sanityFile.asset, {projectId: sanityConfig.projectId, dataset: sanityConfig.dataset})
console.log(fileUrl)
}
Thanks and anything helps!
I found the solution. The buildFileUrl() function exported by #sanity/asset-utils expects a different asset object. Instead, a user in this situation should use the getFileAsset() function which can accept a reference to the file.

Reading JSON data from JS file

I am uploading one JS file using HTML input file tag. I am reading the data in Python. Since in my data var acb_messages is written, I am not able to parse it. And I want to use this variable name to get the data so I can remove it.
var acb_messages = {"messages": [{
"timestamp": 1475565742761,
"datetime": "2016-10-04 12:52:22 GMT+05:30",
"number": "VM-449700",
"id": 1276,
"text": "Some text here",
"mms": false,
"sender": false
}
]}
How can I parse it in Python and then how can I use it?
Two approaches that I would try if I were at your place -
Convert my .js file to .json file and then using method suggested by #Sandeep Lade.
Reading .js file as string, cropping out the value part and then using json.loads(<cropped part>) as suggested by #rahul mr.
Here is how to achieve 2nd solution -
import json
with open('your_js_file.js') as dataFile:
data = dataFile.read()
obj = data[data.find('{') : data.rfind('}')+1]
jsonObj = json.loads(obj)
What's happening here is that you are finding first reading your .js file (that contains js object that needs to be converted into json) as string, find first occurence of { and last occurence of }, crop that part of string, load it as json.
Hope this is what you are looking for.
Warning - Code works only if your js file contains js object only.
The options above are correct, but the JSON syntax in JS can be a little different than in Python:
example.js:
property.docs = {
messages: {
timestamp: 1475565742761,
datetime: "2016-10-04 12:52:22 GMT+05:30",
number: "VM-449700",
id: 1276,
text: "Some text here",
mms: false,
sender: false
}
};
Therefore we need one more tweak that I found at: How to convert raw javascript object to python dictionary?
The complete code should be:
import json
import demjson
with open('example.js') as dataFile:
data = dataFile.read()
json_out = data[data.find('{'): data.rfind('}')+1]
json_decode = demjson.decode(json_out)
print(json_decode)
import json
jsonfile=open("/path/to/json file")
data=json.load(jsonfile)
the above code will store will store your json data in a dictionary called data. You can then process the dictionary

How to set the value received from the response to .js or json file

I am using the karate api framework to automate web services.
Currently, I am facing problem to set the response value back to the .js or JSON file which I receive from the cucumber feature file.
My response:{"authorizationtoken" : "58102a8c9e074d578edae8f3d5e96001'}
How can I save this to .js or JSON file to reuse them in other scripts [feature files] ?
Thanks in advance.
You cannot save the value to a .js or JSON file provided you don't want to write the value to a json file
You can assign the value to a variable , let say using a namespacing technique to avoid collision
var nameSpaceObject = {
authKey : "",
someOtherFunctionIfNecessary :function(){}
};
Then you can call this name space & assign value to it
var response = {"authorizationtoken" : "58102a8c9e074d578edae8f3d5e96001' }
nameSpaceObject.authKey = response.authorizationtoken;

Additional parameters when using intel.xdk.file.uploadToServer?

I'm using Intel XDK to create a smartphone application. Currently I'm uploading a captured photograph by using intel.xdk.file.uploadToServer as shown in their documentation. This is working fully, however I would like to send additional parameters to the back-end (PHP) other than just those required by the 'uploadToServer' function.
What should I do / use?
The uploadToServer file API does not allow you to specify additional parameters than what is documented.
I would use Parse JavaScript APIs that allow you to easily save an object and link to an uploaded file, here is an example:
Parse.initialize("YOUR KEY GOES HERE"); //API key
//whatever you want to call your storage object
var PhotoDetails = Parse.Object.extend("PhotoDetails");
//create new instance of your Parse Object
var photoDetails = new PhotoDetails();
//you can add each param separately and save
photoDetails.set("paramname", "value");
photoDetails.save();
//or use object literal notation
photoDetails.save({category: "landscape",
description: "a very cool photo",
location: "33.38453, -28.234234"
}).then(function(object) {
alert("Photo Recorded!);
});
You can also store the actual photo or filetype in the cloud up to 10MB per file. Parse determines the file type by the file extension or you can specify the type in the optional third param below:
//see https://parse.com/docs/js_guide#files
//for base 64 or HTML file input examples
var parseFile = new Parse.File("myphoto.jpg", fileData, "image/jpg");
parseFile.save().then(function() {
alert("The file has been saved to Parse.");
}, function(error) {
console.log("The file either could not be read, or could not be saved to Parse.");
});
You can associate a Parse File with a Parse Object by using:
photoDetails.set("photoFile", file);
photoDetails.save();
Then in the cloud you can login to Parse and you will see your object type in the Data Browser view with your photo image and all the other params you specified.
For more info see: https://parse.com/docs/js_guide#javascript_guide

JayData upload file

I have a WCF Data Services running and JayData as a client. I now want to upload a file en put it in a blob in the database. I created a entity with a binary scalar property and a string property for the file name.
JaySvcUtil creates my JayDataContext.js just fine like this:
$data.Entity.extend('Entities.Plugin', {
'Id': { 'key':true,'type':'Edm.Int32','nullable':false,'computed':true },
'Data': { 'type':'Edm.Binary','nullable':false,'required':true },
'FileName': { 'type':'Edm.String','nullable':false,'required':true }
});
Does anybody know how to upload a file to WCF Data Service using Javascript?
Thank you
The Data field can be field can be set with Base64 string - JayData 1.3 might offer other options, but the base64 is the way to go with the current stable version (1.2.7).
You can use HTML5 File API to get the Base64 string from your local file.
I hope this helps! Let me know about your results.

Categories