Load a JSON file into a JS object - javascript

I try to load a json file into a JavaScript var but it just doesn't work out.
var jsonString = JSON.stringify('./test.json');
var obj = JSON.parse(jsonString);
console.log(obj.details.ProductID);
it says that it can't read property ProductID of undefined.
What am I doing wrong here ?

You need to make an AJAX call to get the file. $.getJSON was intended for exactly this purpose:
$.getJSON('./test.json', function(obj) {
console.log(obj.details.ProductID);
});

If you are using jQuery:
$.getJSON( "/test.json", function( obj ) {
console.log(obj.details.ProductID);
});

JSON.stringify() first argument needs to be a valid JSON string, not a file.
You need to use AJAX to retrieve file from server:
$.getJSON('./test.json', function(responseObject){
var obj = responseObject
console.log(obj)
})

In case it helps anyone, just use this:
const dataObjectFromFile = require('./path/to/datafile.json');

Related

JSON array-like object, add item

I have a JSON file which contains:
[{"id":1,"first_name":"Judith","email":"jshaw0#wikipedia.org"},
{"id":2,"first_name":"Sarah","email":"sross1#infoseek.co.jp"},
{"id":3,"first_name":"Dorothy","email":"dgreene2#posterous.com"},
{"id":4,"first_name":"Christine","email":"cnichols3#techcrunch.com"},
{"id":5,"first_name":"Theresa","email":"trogers4#xrea.com"},
{"id":6,"first_name":"Rebecca","email":"rpeterson5#mlb.com"},
{"id":7,"first_name":"Chris","email":"cbailey6#yellowpages.com"},
{"id":8,"first_name":"Howard","email":"hbailey7#miibeian.gov.cn"},
{"id":9,"first_name":"Sara","email":"ssimpson8#techcrunch.com"},
{"id":10,"first_name":"Lois","email":"lmartinez9#dion.ne.jp"},
{"id":11,"first_name":"Jeffrey","email":"jhalla#intel.com"},
{"id":12,"first_name":"Teresa","email":"tcampbellb#usnews.com"},
{"id":13,"first_name":"Susan","email":"skingc#wired.com"},
{"id":14,"first_name":"Richard","email":"rpattersond#omniture.com"},
{"id":15,"first_name":"Ronald","email":"rgreenee#wordpress.org"}]
I want to add one more element to it but I can't figure it out how.
I have the following node code:
var jsonfile = require('jsonfile');
var util = require('util');
var file = 'data.json';
var jsonObj = {};
jsonfile.readFile(file, function(err, obj) {
jsonObj = obj;
new_obj = {"id":16,"first_name":"Florin","email":"popflorin1705#yahoo.com"};
//jsonObj.push(new_obj)
console.log(typeof jsonObj);
/*jsonfile.writeFile(file, jsonObj, function (err) {
console.error(err)
})*/
});
I've tried to use push method, but obviously is not working because it is an object not an array, even if it looks as an array. Which would be a good way to add another row at the end of the object (or array - I'm confused)?
I believe you're forgetting to parse JSON. After reading the file, your code should be:
jsonObj = JSON.parse(obj);
instead of straight assignment.
Declare the variable
var new_obj = {"id":16,"first_name":"Florin","email":"popflorin1705#yahoo.com"};
And then use push() as you have done already. Give it a try. It will work only if obj is json object as you mentioned in question.

How to serialize File object to JSON? [duplicate]

I want to convert an HTML input file to a JSON string like this:
var jsonString = JSON.stringify(file);
console.log( file );
console.log( jsonString );
Now, in my Firebug it logs as:
File { size=360195, type="image/jpeg", name="xyz.jpg", mehr...}
Object {}
Why is the jsonString empty?
Background info: I want to send the file-reference with JSONP to another PHP server.
Additional Information: I want to convert only the file-pointer (reference) to a string, to send it via GET.
It is not possible to directly convert a File object into JSON using JSON.stringify in Chrome, Firefox and Safari.
You can make a work around to convert File object to string using JSON.stringify
Ex:
// get File Object
var fileObject = getFile();
// reCreate new Object and set File Data into it
var newObject = {
'lastModified' : fileObject.lastModified,
'lastModifiedDate' : fileObject.lastModifiedDate,
'name' : fileObject.name,
'size' : fileObject.size,
'type' : fileObject.type
};
// then use JSON.stringify on new object
JSON.stringify(newObject);
You can also add the toJSON() behavior to your File object
EX:
// get File Object
var fileObject = getFile();
// implement toJSON() behavior
fileObject.toJSON = function() { return {
'lastModified' : myFile.lastModified,
'lastModifiedDate' : myFile.lastModifiedDate,
'name' : myFile.name,
'size' : myFile.size,
'type' : myFile.type
};}
// then use JSON.stringify on File object
JSON.stringify(fileObject);
Note: send a File Object to server using the POST HTTP method.
You have to read the file content using the FileReader API. The File object does not contain the file content (it is just a pointer toward the file, which allows you to read it later).
You can check out this HTML5Rocks article to find out more about the usage of this API.
var file = getAFile( );
var success = function ( content ) {
console.log( JSON.stringify( content ) ); }
var fileReader = new FileReader( );
fileReader.onload = function ( evt ) { success( evt.target.result ) };
fileReader.readAsText( file );
In case anyone is still looking for a solution to this please see my answer on a different post and working example on JSFiddle.
JS:
function getFiles(){
var files = document.getElementById("myFiles").files;
var myArray = [];
var file = {};
console.log(files); // see the FileList
// manually create a new file obj for each File in the FileList
for(var i = 0; i < files.length; i++){
file = {
'lastMod' : files[i].lastModified,
'lastModDate': files[i].lastModifiedDate,
'name' : files[i].name,
'size' : files[i].size,
'type' : files[i].type,
}
//add the file obj to your array
myArray.push(file)
}
//stringify array
console.log(JSON.stringify(myArray));
}
HTML:
<input id="myFiles" type="file" multiple onchange="getFiles()" />
You just need a custom replacer:
function stringify(obj) {
const replacer = [];
for (const key in obj) {
replacer.push(key);
}
return JSON.stringify(obj, replacer);
}
const json = stringify(file);
console.log(file);
console.log(json);
Now you should see:
FileĀ {name: "xyz.jpg", type: "image/jpeg", size...}
'{"name":"xyz.jpg","type":"image/jpeg","size"...}'
Instead of looping through, or rather extracting each key one after the other, i came up with this function and i've used it image input.
const fileObject = e.target.files[0];
important notice
//dont use shorthand for of loop
for (const [key, value] in Object.entries(x))
it can't loop through a file object in JS
Use this code instead
const imageObject = {};
for (const key in fileObject) {
const value = fileObject[key];
const notFunction = typeof value !== "function";
notFunction && (imageObject[key] = value);
}
console.log(imageObject) // => should give you a normal JS object now
When you pass a json string Javascript internally trnsform it to Json object and hence no need to parse it.
follow steps in case of of json file ->
$('#inp_import_template')[0].files[0]
Now your json file is transformed to json object (Javascript).
var obj = {
name: 'dashu3f'
};
var stringObj = JSON.stringify(obj);
console.log(typeof stringObj);
console.log(stringObj);
open terminal this Folder file and run node json.js

How can I serialize an input File object to JSON?

I want to convert an HTML input file to a JSON string like this:
var jsonString = JSON.stringify(file);
console.log( file );
console.log( jsonString );
Now, in my Firebug it logs as:
File { size=360195, type="image/jpeg", name="xyz.jpg", mehr...}
Object {}
Why is the jsonString empty?
Background info: I want to send the file-reference with JSONP to another PHP server.
Additional Information: I want to convert only the file-pointer (reference) to a string, to send it via GET.
It is not possible to directly convert a File object into JSON using JSON.stringify in Chrome, Firefox and Safari.
You can make a work around to convert File object to string using JSON.stringify
Ex:
// get File Object
var fileObject = getFile();
// reCreate new Object and set File Data into it
var newObject = {
'lastModified' : fileObject.lastModified,
'lastModifiedDate' : fileObject.lastModifiedDate,
'name' : fileObject.name,
'size' : fileObject.size,
'type' : fileObject.type
};
// then use JSON.stringify on new object
JSON.stringify(newObject);
You can also add the toJSON() behavior to your File object
EX:
// get File Object
var fileObject = getFile();
// implement toJSON() behavior
fileObject.toJSON = function() { return {
'lastModified' : myFile.lastModified,
'lastModifiedDate' : myFile.lastModifiedDate,
'name' : myFile.name,
'size' : myFile.size,
'type' : myFile.type
};}
// then use JSON.stringify on File object
JSON.stringify(fileObject);
Note: send a File Object to server using the POST HTTP method.
You have to read the file content using the FileReader API. The File object does not contain the file content (it is just a pointer toward the file, which allows you to read it later).
You can check out this HTML5Rocks article to find out more about the usage of this API.
var file = getAFile( );
var success = function ( content ) {
console.log( JSON.stringify( content ) ); }
var fileReader = new FileReader( );
fileReader.onload = function ( evt ) { success( evt.target.result ) };
fileReader.readAsText( file );
In case anyone is still looking for a solution to this please see my answer on a different post and working example on JSFiddle.
JS:
function getFiles(){
var files = document.getElementById("myFiles").files;
var myArray = [];
var file = {};
console.log(files); // see the FileList
// manually create a new file obj for each File in the FileList
for(var i = 0; i < files.length; i++){
file = {
'lastMod' : files[i].lastModified,
'lastModDate': files[i].lastModifiedDate,
'name' : files[i].name,
'size' : files[i].size,
'type' : files[i].type,
}
//add the file obj to your array
myArray.push(file)
}
//stringify array
console.log(JSON.stringify(myArray));
}
HTML:
<input id="myFiles" type="file" multiple onchange="getFiles()" />
You just need a custom replacer:
function stringify(obj) {
const replacer = [];
for (const key in obj) {
replacer.push(key);
}
return JSON.stringify(obj, replacer);
}
const json = stringify(file);
console.log(file);
console.log(json);
Now you should see:
FileĀ {name: "xyz.jpg", type: "image/jpeg", size...}
'{"name":"xyz.jpg","type":"image/jpeg","size"...}'
Instead of looping through, or rather extracting each key one after the other, i came up with this function and i've used it image input.
const fileObject = e.target.files[0];
important notice
//dont use shorthand for of loop
for (const [key, value] in Object.entries(x))
it can't loop through a file object in JS
Use this code instead
const imageObject = {};
for (const key in fileObject) {
const value = fileObject[key];
const notFunction = typeof value !== "function";
notFunction && (imageObject[key] = value);
}
console.log(imageObject) // => should give you a normal JS object now
When you pass a json string Javascript internally trnsform it to Json object and hence no need to parse it.
follow steps in case of of json file ->
$('#inp_import_template')[0].files[0]
Now your json file is transformed to json object (Javascript).
var obj = {
name: 'dashu3f'
};
var stringObj = JSON.stringify(obj);
console.log(typeof stringObj);
console.log(stringObj);
open terminal this Folder file and run node json.js

Javascript array into jQuery .post AJAX call

I have a JAVASCRIPT array that looks like this:
postarray['min_price'] = 120000;
postarray['max_price'] = 150000;
I'm trying to pass this to an AJAX call via jQuery .post function so that the .PHP file gets it in this format:
$_REQUEST['query']['min_price'] = 120000;
$_REQUEST['query']['max_price'] = 150000;
So far I've tried:
$.post("ajax_findproperties.php", {query: postarray},
function(data){
// processing function with JSON result
}
,'json');
But I've had no luck. I even tried changing the var postarray to query and then tried query.serialize() in place of the bracketed variable block, but with no luck either.
When I check my status on Firebug, the AJAX call has absolutely no POST vars set whatsoever - complete blank.
The javascript array is not an array, it's an object. Define it before:
var postarray = {};
postarray['min_price'] = 120000;
postarray['max_price'] = 150000;
or replace with:
var postarray = {
min_price: 120000,
max_price: 150000
};
Now the JSON.stringify works:
alert(JSON.stringify(postarray));
Also see this example.
But this object should also be send without JSON.stringify():
$.post("ajax_findproperties.php", {query: postarray}, ... );
Have you tried converting it with JSON.stringify(); and then doing a json_decode(...); in the PHP script?
Try this solution : add [] to your query key
$.post("ajax_findproperties.php", { 'query[]': postarray },
function(data) { },
'json');
Source : http://api.jquery.com/jQuery.post/#example-2

JSON parse issue

I have a JSON string like this:
{"time":"2011-11-30 04:44","countryName":"Austria","sunset":"2011-11-30 16:32","rawOffset":1,"dstOffset":2,"countryCode":"AT","gmtOffset":1,"lng":10.2,"sunrise":"2011-11-30 07:42","timezoneId":"Europe/Vienna","lat":47.01}
How can I parse this using javascript? I have tried using:
function callbackFun(data) {
$j.each(data.result, function(i, item) {
alert(this.time);
});
}
But it seems this is not correct.
If you retrieve that piece of data from $.ajax() then you could set up dataType: 'json' to get it automatically parsed for you.
Otherwise just use $.parseJSON()
If you're using jQuery, it's trivial:
var obj = '{"time":"2011-11-30 04:44","countryName":"Austria","sunset":"2011-11-30 16:32","rawOffset":1,"dstOffset":2,"countryCode":"AT","gmtOffset":1,"lng":10.2,"sunrise":"2011-11-30 07:42","timezoneId":"Europe/Vienna","lat":47.01}';
var json = jQuery.parseJSON(obj);
alert(json.time);
alert(json.countryName);
http://api.jquery.com/jQuery.parseJSON/
Are you looking for this?
var MyJson = '{"time":"2011-11-30 04:44","countryName":"Austria","sunset":"2011-11-30 16:32","rawOffset":1,"dstOffset":2,"countryCode":"AT","gmtOffset":1,"lng":10.2,"sunrise":"2011-11-30 07:42","timezoneId":"Europe/Vienna","lat":47.01}';
var MyObject = jQuery.parseJSON(MyJson);

Categories

Resources