Can I generate a JSON file with javascript?

25,835

Solution 1

To parse a JSON object with Javascript, I would use jQuery.

http://api.jquery.com/jQuery.parseJSON/

Like anthonybell said most browsers do not allow cross-site scripting so you need to look into jsonP or work on the same domain.

Also to generate JSON you can create an object using javascript then either loop though it and output it or just output your data in JSON format which you can read about here:
http://www.w3schools.com/json/

Solution 2

json is just a javascript object in a string format so javascript can make json data:

   var animal = {name: "cat", sound: "meow"};
   json = JSON.stringify(animal); //json is a JSON string

javascript does not allow ajax calls across to other sites (cross-site scripting) though becuase it is a security risk. you could look into jsonP which is a work-around this rule.

Also you cannot call to another website or your own server to run javascript to return something becuase javascript only runs in the clients browser (unless you are using a javascript server like node.js). A server has to be listening somewhere for a request.

Share:
25,835
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    I want to make a page on domain "example1.com" and get/parse a JSON file on another domain "example2.com/json.json". Can the json file be generated with javascript (on example2.com)? I think this can be done with php, but I want to do it with javascript. If it is not possible to generate a json file with javascript, is it possible to get/parse an object from a javascript file? EX: "example1.com" to "example2.com/js.js"

    EDIT: Ok, so it is not possible to get/parse an object from a javascript file, because it is client side. So my only option is to generate a JSON file. Is it possible to do that with Javascript? I know it's probably not the best way, but I want to do it in JS, not PHP.