Error saving JSON file - javascript

I have following JSON file:
weather = [
{
"city": "Munich",
"temp": {
"temp_val": "30 deg",
"temp_unit": "C"
},
"speed": {
"speed_val": 7.31,
"speed_unit": "m/s"
}
}
]
I am new to working with JSON files. I want to save this JSON file as weather.json.
But it gives following error:
Expected value at 1:0 pointing to the first line of the file.

You can't have weather = in your JSON file. JSON stands for JavaScript Object Notation so anything other than a JavaScript Object won't work. You also can't have functions in there. Take a look at the JSON official website to see what the format accepts
This should be correct:
[
{
"city": "Munich",
"temp": {
"temp_val": "30 deg",
"temp_unit": "C"
},
"speed": {
"speed_val": 7.31,
"speed_unit": "m/s"
}
}
]
You can then add this line in your javascript once you load the file into a string:
weather = JSON.parse(some_string);

You are manipulating this file as if it was going to be rendered as JavaScript. This should only be plain text, no variable definitions. Just plain key value pairs. If you want to assign variable, set it to a .js file and render it in a browser.
You should look at an example file for JSON and model it. Remember that JSON is just plain text organized in a particular way.

Related

Need to print data from an xml response in postman?This xml is a bit strange one

1.I need to do api testing.
2.Here is the xml response given by the server.
3.I need to extract the data of partID,partBrand,quantityAvailable and store it
in an environment variable's and also print it in console.
4.I'm using Postman tool in chrome and used java
script code to perform some tests.
5.Please provide a solution to extract data from this xml.
<Reply
xmlns="">
<productID>G500</productID>
<ProductVariationInventoryArray>
<ProductVariationInventory>
<partID>B11007514</partID>
<partDescription>g500 BLACK M</partDescription>
<partBrand>Gildan</partBrand>
<quantityAvailable>72105</quantityAvailable>
<attributeColor>BLACK</attributeColor>
<attributeSize>M</attributeSize>
<validTimestamp>2017-11-23T05:31:39.689-05:00</validTimestamp>
</ProductVariationInventory>
</ProductVariationInventoryArray>
</Reply>
Here is the code after converting it to json object using "xml2Json(responsebody)"
{
"Reply": {
"productID": "G500",
"ProductVariationInventoryArray": {
"ProductVariationInventory": {
"partID": "B11007514",
"partDescription": "g500 BLACK M",
"partBrand": "Gildan",
"quantityAvailable": "72105",
"attributeColor": "BLACK",
"attributeSize": "M",
"validTimestamp": "2017-11-23T05:31:39.689-05:00"
}
}
}
}
Now,I need to extract the data of partID,partBrand,quantityAvailable and store it in an environment variable's and also print it in console.

File Naming Conventions .json or .js?

So, I'm trying to create some helpful JSON files that other can use to prototype out applications using State JSON data with image names that correspond to actual images I have in the same directory.
Here are my files : https://github.com/tannerjt/state_images.json
My question is this... since JSON is just javascript, should I use .json or .js for files.
One of my files is technically JSON, but I named it states.js, since it is an array of javascript object...
[
{
"name": "Alabama",
"abbreviation": "AL",
"capital": "",
"image": {
"image_name": "alabama.jpg",
"location": "Monte Sano State Park",
"credit": {
"author": "Wes Thomas (BamaWester on Flickr)",
"url": "http://www.flickr.com/photos/bamawester/3493269235/"
}
}
},....
]
Because I called it a .js file, I added
var states = [{...
to the beginning. With it being an Array of json object... JSONlint still validated it.
Any thoughts? I want to make this useful for people to play around with, but not sure how I name the files correctly.
if you included var states = [{... in your raw text and tried to parse the thing as a json object, it would probably fail. Saving it as a .json file and leaving it only with data would be a preferred option.

Deleting elements out of a json file without getting "null"

I have a JSON formatted text file that I'm using as kind of a database.
I read the file, use JSON.parse to turn it into an object, use delete on an element, then I JSON.stringifythe object and write it back to the file.
However the resulting file has "null" in the place where the object used to be, which isn't proper JSON, so my program will crash the next time the file is parsed. I don't like it.
How can I delete elements from my file without getting "null" where the element used to be?
Here's how I do it:
data = fs.readFileSync("./manifest/test.json");
contents=JSON.parse(data);
//some logic
delete contents.customers[i].files[j];
fs.writeFileSync("./manifest/test.json",JSON.stringify(contents,null,4));
And the resulting file before:
{
"customers": [
{
"customer": "test",
"files": [
{
"name": "test.flv",
"location": "cloudfront.url.com/check.flv"
}
]
}
]
}
And after:
{
"customers": [
{
"customer": "test",
"files": [
null
]
}
]
}
contacts.customers[i].files.splice(j, 1);
The result is still valid JSON though. JSON.parse should succeed. The error may lie elsewhere.

View json parse object structure in eclipse javascript

I would like to view the json parse objects structure in eclipse. Due to the cross domain issue I am unable to use the console.log() to view the structure in chrome. How else can I view this [object Object] returned structure from Json.Parse ?
Use JSON.stringify(object), it will convert your object to a string(then you can alert, write or whatever you want).
EDIT
If this is the returned value from the request:
'{"Date":"05\/25\/2013","Description":"New2","Details":"New2","Item‌​RequestedID":"1343","Picture":,255,217],"Status":1,"User":"2120","Use‌​rName":"Ind1"}'
It is not yet parsed, so you need to use JSON.parse(string) to parse it to a valid JS Object. Once it is parsed, this will be the structure of your object:
{
"Date": "05\/25\/2013",
"Description": "New2",
"Details": "New2",
"Item‌​RequestedID": "1343",
"Picture": ,
255,
217], "Status": 1,
"User": "2120",
"Use‌​rName": "Ind1"
}
var obj = JSON.parse(result)//where result is the string above and obj is the parsed object with this structure
Then you will be able to access what you need doing obj.Date, obj.Description etc

Parse JSON from local url with JQuery

I have a local url where i can retrieve a json file. I also have a simple website which is build using JQuery.
I've looked up many sites for tutorials and sample code on how to retrieve the json input and parse it so i can display it on my site. However non were helpful as i still can't make it work.
So as a last resort i'm going to ask stackoverflow for your help. I have a lot of java knowledge, but I'm relative new to 'web'-development and know some basics of javascript.
This is a sample output of my url:
[
{
"baken": "not implemented...",
"deviceType": "Optimus 2X",
"batteryLevel": "1.0",
"gps": {
"speed": 0,
"Date": "TueNov0100: 34: 49CET2011",
"Accuracy": 35,
"longitude": {removed},
"latitude": {removed},
"Provider": "gps"
},
"deviceId": "4423"
},
{
"baken": "notimplemented...",
"deviceType": "iPhone",
"batteryLevel": "30.0",
"gps": {
"speed": 0,
"Date": "TueNov0116: 18: 51CET2011",
"Accuracy": 65,
"longitude": {removed},
"latitude": {removed},
"Provider": null
},
"deviceId": "4426"
}
]
Hope you can help me..
If you are running a local web-server and the website and the json file are served by it you can simply do:
$.getJSON('path/to/json/file.json', function(data) {
document.write(data);
})
If you are just using files and no webserver you might get a problem with the origin-policy of the browser since AJAX request cannot be send via cross-domain and the origin domain is 'null' per default for request from local files.
If you are using Chrome you can try the --allow-file-access-from-files parameter for developing purposes.
Your URL returns invalid json. Try pasting it in jsonlint.com and validating it there and you'll see what I mean. Even the code highlighting here on stackoverflow is showing you what's wrong. :)
Edit: To parse it you can use jQuery.parseJSON
jQuery.parseJSON('{"foo": "goo"}');
$.get('/some.json', function(data) {
// data[0]["baken"] == "not implemented..."
});
See http://api.jquery.com/jQuery.get/
You don't need to parse the json -- that is why people like it. It becomes a native JavaScript object.
For your example if you put the results in a variable called data then you could do things like this:
data[0].deviceType // would be "Optimus 2x"
data[0].gps.speed // would be numeric 0
etc.
The most natural way is to allow jQuery to make an AJAX call for you once you've already entered the page. Here's an example:
$.ready(function() {
// put your other code for page initialization here
// set up a global object, for namespacing issues, to hold your JSON.
// this allows your to be a good "web" citizen, because you will create
// one object in the global space that will house your objects without
// clobbering other global objects from other scripts, e.g., jQuery
// makes the global objects '$' and 'jQuery'
myObjects = {};
// start JSON retrieval here
$.getJSON('/path/to/json/file.json', function(data) {
// 'data' contains your JSON.
// do things with it here in the context of this function.
// then add it to your global object for later use.
myObjects.myJson = data;
});
});
The API documentation is here

Categories

Resources