Convert JavaScript file to JSON [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to parse JSON in Android
I am writing an Android app where I'm getting a .js (JavaScript) file from a url and I want to read its contents. Is there any way to convert this file to a JSONArray or JSONObject? Or a direct way to parse the .js file itself?

If you mean can you create a data structure out of raw JavaScript, then no.
You can't convert a string of arbitrary JavaScript to JSON except in the degenerate sense that the entire string is a valid JSON item of type 'string'. This is because the syntax of JS covers a much larger domain than JSON. For example, what kind of JSON structure would you expect to represent the following JS?
while (true) { }
If your intent is to traverse the JS and pull data structures out of it, you're probably going to need something like a full JavaScript parsing engine.
If on the other hand you've phrased the question badly and the '.js' file you're fetching is really a JSON file, then the question is answered in the marked duplicate.

Related

Are there benefits to re-defining JSON data as JavaScript objects in source code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm loading a JSON file from a web server via the XMLHttpRequest in JavaScript. This module, or alternatively the JSON.parse method, returns a JSON Object (a regular JavaScript object, which I call JSON Object as w3schools does).
Loaded JSON data:
{
"MyName":"Kiwi",
"MyNum" : "42",
"MyList" : {
"$type" :"Bla",
"$values: [ ]
}
};
I can pass around the parsed object and access it's properties like a regular JavaScript object. However, I'm wondering if it would make sense to actually declare the object's properties in source code such as:
// MyObject.js
function MyObject() {
this.myName = "Kiwi";
this.myNum = 42;
this.myList = []
}
And basically, map each property from my parsed JSON object to the JavaScript object declared in source code like so (plus additional transformations):
var myObj = new MyObject();
myObj.myName = jsonObject.MyName;
myObj.myNum = jsonObject.MyNum;
I would assume this has benefits such as:
Actual type information such as numbers vs strings
Potentially intellisense/auto-complete features in my IDE
Easier upgrading of data, if the JSON properties ever change
I'm comparing my approach to how JSON is parsed and turned into objects in a language such as C#, using a serializer such as JSON.NET.
Is this also common practice in the JavaScript world or should I stick to just using the JSON objects returned by the JSON.parse method?
Further info:
My special use-case is the handling of JSON data, which includes many meta fields (denoted by names such as "$type" or "$values" to indicate an array). The files were created by JSON.NET and serialize C# objects, which I basically mirror in my JavaScript application. Hence, I might want to re-declare properties more similar to the way the original C# classes were declared. Mainly this would turn calls like myObject.aList.$values[0] into myObject.aList[0].
If you need more than the data types JSON provides, you can roll something yourself to process the items that JSON.parse spits out, or use many libraries like this one
Most peoples use cases are simple enough that they won't need a library that supports more 'rich' data storage, and JSON is fine.
If you know the data structure ahead of time, and need to convert for example a JSON date (stored as a string) into a Javascript date, it's best to just convert it upon loading the JSON. If you have complex needs requiring loading complex data types that you won't be able to predict ahead of time, use a library like Transit.js

How to pass a string which contain UTF-8 characters from javascript to PHP? [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
How to store other languages (unicode) in cookies and get it back again
(1 answer)
Closed 5 years ago.
I'm building a references generator and I need to keep track of the generated references. To achieve this, I'm currently using Javascript to store a cookie containing the raw data, then a PHP page embedded on the result page takes the cookie and logs it into an HTML page, however, some characters appears like this : �. I really don't know which way to go to solve this (base64 encoding, unicode encoded characters...)
Here's the link to the website : http://louisfelixberthiaume.000webhostapp.com/source_siteweb.php
[It's in french]
I can't give you the link to the HTML page for obvious confidentiality reasons, however I'll provide a screenshot :
Generated references screenshot

Copy Javascript-Code into PHP [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
I have a problem...
I want to send a Javascript-Document-Code with a Mail-function...
The PHP-Code looks like this:
$script = '<script>
vfprintf(handle, format, args)ar hljs=new function(){function k(v){return v.replace(/&/gm,\"&\").replace(/</gm,\" ect...
</script>';
(It would be too log to post it all, 30.000 characters...)
How can I assure, that the Special-Characers (", ', \, //, ...) are escaped? :s
EDIT:
This is not a duplicate of the thread, please read it carefully!
Code in one language which emits code in another language is a notoriously difficult thing when it comes to escaping "special" characters. When that code gets upward of tens of thousands of characters then it makes a lot more sense to store it in another file which would be appropriate for that language. In this case, a .js file.
That file can be maintained as that language and not as just a literal string in PHP. This gives you things like syntax checking, debugging, testing, etc.
If the end result (such as a web page or some other displayed HTML) can simply refer to that file separately, then host the file somewhere and just send a reference to it (such as a script tag in the case of HTML). The end user's system will download the file accordingly.
If the end result needs to have this content directly embedded, then in PHP you'd read the file's contents into a string and emit that. Something like file_get_contents('yourScript.js').
Treat code as code, not as string literals.

Pass an array from .jsp file to .js file [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to transfer java array to javaScript array using jsp?
After googling I am still not able to pass array from .jsp file to js file.
Can somebody help me out?
In my .jsp file i have an array and I wan to call a function in .js file which accepts this array. How to call this function?
By passing an array from .jsp to js file I guess you mean your Javascript script needs to "call" a script return by a JSP file. And that script contains a function that returns an array?
If so have you looked at returning JSON from your JSP?
For simple arrays, you can convert the array to a comma-delimited string using an implode function, pass the string to javascript, and then use split(str) in Javascript to get an array back. More complicated arrays may cause issues with this.

Howto convert E4X XML Elements into JSON Notation [duplicate]

This question already has answers here:
Convert XML to JSON (and back) using Javascript
(14 answers)
Closed 8 years ago.
I have a server Implementation of ECMA Script including the ability to use E4X. Because this is pretty elegant for people don't know JavaScript and JSON Notation and we want to make an API which is most easy to learn i want to use this for my API.
I'm currently evaluating if i can use this in my environment. One Showstopping feature that i must use is to convert those XML Objects of E4X into JSON compatible JavaScript Objects or Strings on the fly. I can't use XSLT here because i have to stay inside JavaScript.
So the question is, is there an easy way to convert E4X XML Elements into JSON? Or do i have to write some code to convert it myself?
You can use XSLT to convert your XML to JSON.
For instance using: http://code.google.com/p/xml2json-xslt/
However you can end up with a very XMLish and unnecessarily complex JSON. That will make your code more difficult to write and maintain.
An API is generally meant to be stable in time, so may be some dedicated XSLT for each calls may be a better option than a generic one.

Categories

Resources