I got into a little thing while getting a JSON file from a server, the JSON file contains something like this:
var reviews = [
{
"firstName":"Simon",
"lastName":"Lock",
"fullName":"Simon Lock",
"location":"San Francisco",
"reviewTitle":"Super quality.. I will show here again!",
"reviewBody":"Super nice quality, fast devilery, good prices. I will shop here again!",
"starRating":"5"
},
{
"firstName":"John",
"lastName":"Smith",
"fullName":"John Smith",
"location":"New York",
"reviewTitle":"Princely Sum",
"reviewBody":"A decent local curry house in Faversham, Kent known for its Elvis nights.",
"starRating":"4"
},
];
And as expected, I get an error while getting the file with $.ajax:
SyntaxError: Unexpected token v
Since is not a valid JSON format, but I did also try to do it with another kind of dataType.
My question is:
Is there any way to get that variable in JSON file stored in another variable so it can be manipulated normally?
also I did try to use FileReader() but I didn't work for me.
thanks
JSON is just a way of storing data, not JavaScript code. it doesn't know what to do with var reviews =. All you store in your JSON file is the data, like below.
[
{
"firstName":"Simon",
"lastName":"Lock",
"fullName":"Simon Lock",
"location":"San Francisco",
"reviewTitle":"Super quality.. I will show here again!",
"reviewBody":"Super nice quality, fast devilery, good prices. I will shop here again!",
"starRating":"5"
},
{
"firstName":"John",
"lastName":"Smith",
"fullName":"John Smith",
"location":"New York",
"reviewTitle":"Princely Sum",
"reviewBody":"A decent local curry house in Faversham, Kent known for its Elvis nights.",
"starRating":"4"
}
]
Bear in mind that this is not something I recommend in cases where security is critical, but you do have the option of using the eval() function on the plain text of the file.
eval('var reviews = [
{
"firstName":"Simon",
"lastName":"Lock",
"fullName":"Simon Lock",
"location":"San Francisco", ...
would give you a variable reviews that contains the object you want.
edit: yes eval is evil, I know
Related
I am trying to parse a JSON from a GET request in JavaScript. I can run it through JSONLint and other tools and it's fine. If I copy/paste the exact result into the JavaScript I can access the values from the object as well.
Here is a shortened example of what the JSON structure looks like:
{
"odata.metadata": "EXAMPLE.com/$metadata#EXAMPLE.results",
"value": [{
"SerialNo_Company": "1",
"Calculated_AsBuilt": "AsBuilt",
"SerialNo_SerialNumber": "1",
"SerialNo_PartNum": "2A",
"JobHead_RevisionNum": "A",
"JobMtl_MtlSeq": 30,
"JobMtl_PartNum": "A123",
"JobMtl_RevisionNum": "A",
"JobMtl_Description": "KEY",
"JobMtl_QtyPer": "1.00000000",
"JobMtl_IUM": "EA",
"JobHead_JobNum": "13",
"JobMtl_IssuedQty": "2.00000000",
"JobMtl_RequiredQty": "2.00000000",
"RowIdent": "7e91b43a-897c-49b4-b68f-307b9ba74832"
}, {
"SerialNo_Company": "1",
"Calculated_AsBuilt": "AsBuilt",
"SerialNo_SerialNumber": "1",
"SerialNo_PartNum": "2A",
"JobHead_RevisionNum": "A",
"JobMtl_MtlSeq": 30,
"JobMtl_PartNum": "A123",
"JobMtl_RevisionNum": "A",
"JobMtl_Description": "KEY",
"JobMtl_QtyPer": "1.00000000",
"JobMtl_IUM": "EA",
"JobHead_JobNum": "14",
"JobMtl_IssuedQty": "2.00000000",
"JobMtl_RequiredQty": "2.00000000",
"RowIdent": "6251fbaf-36d0-4fcf-b65a-9dde70ffb13d"
}]
}
This format isn't entirely correct though, what it actually outputs has a structure like so:
"{\r\n \"odata.metadata\":\"EXAMPLE.com/$metadata#Example.results\",\"value\":[\r\n {\r\n \"SerialNo_Company\":\"1\",\"Calculated_AsBuilt\":\"AsBuilt\",\"SerialNo_SerialNumber\":\"1\",\"SerialNo_PartNum\":\"2A\",\"JobHead_RevisionNum\":\"A\",\"JobMtl_MtlSeq\":30,\"JobMtl_PartNum\":\"A13518N-28-KS\",\"JobMtl_RevisionNum\":\"A\",\"JobMtl_Description\":\"KEY\",\"JobMtl_QtyPer\":\"1.00000000\",\"JobMtl_IUM\":\"EA\",\"JobHead_JobNum\":\"13\",\"JobMtl_IssuedQty\":\"2.00000000\",\"JobMtl_RequiredQty\":\"2.00000000\",\"RowIdent\":\"111531e1-f4da-4d2d-b980-0074227a474e\"\r\n }\r\n ]\r\n}
When I try to query the first structure when hard coded in javascript, for example
object.value[0]
I get the first value and all is good.
The second one does not return a value with the same query. I removed the \r\n and it did not work. Also, JSON.stringify() puts in a bunch of backslashes in the structure and I don't know why.
Thanks for reading if you made it this far, please help.
The solution was to change the output in my node.js app. I was using res.json() and it was double-encoding the response. The output resulted in a javascript readable format from there. Thanks to Heretic Monkey for the answer
I'm trying to access data within a json file using nodeJS
When I run this I get the error : TypeError: Cannot read property 'postcode' of undefined. Any Suggestions?
{
"apiName": "Restaurants",
"pages": [
{
"pageUrl": "https://url",
"results": [
{
"address": "3F Belvedere Road Coutry Hall, London, SE17GQ",
"phone": "+442076339309",
"name": "Troia",
"postcode": "SE17GQ"
}
]
}
]
}
var myData = require('./jsonFile.json');
console.log(myData.pages.result.postcode);
Try to access data as below:
console.log(myData.pages[0].results[0].postcode);
The value in the bracket is the index of element to access.
Its the common singular/plural trap, I fall for it all the time.
In your json, pages & results are arrays. You need to access these with an index. Also, you have a typo in the name.
Try this:
console.log(myData.pages[0].results[0].postcode);
This will gave you correct answer.
console.log(myData.pages[0].results[0].postcode);
I have a ajax server response
{
"applicationBankList": [
{
"id": "${addressId}",
"accountNumber": "",
"accountName": "",
"paymentMethodCode": "DRDEB",
"name": "BANKOFENGLAND",
"yearsWithBank": "8",
"bankSortCode": "100000",
"monthsWithBank": "8",
"branch": "HeadOffice",
"sortCode": "10-00-00",
"validationInformation": "",
"validationStatus": ""
}
],
"applicationBillingAddress": {
"defaultFlag": "Y"
}
}
I need to make it much human readable by aligning them properly, i have huge set of responses its quite very hard to read them so i am looking for a solution which automatically formats for human readability
is there any solution for this
Just wanting it pretty defeats the purpose of using json. It's meant to be compact, adding spaces, line breaks, and indents, goes against the grain.
If you want to debug or check the structure of it: http://jsonlint.com/
I think making it "human-readable" has to be done on the server-side. What you are getting is the server-response, the way it is sent. Do you have access to the server code that returns the response string?
I have an XML file with the following content:
<directory>
<app>
<title>Carrot</title>
<url>www.carrot.com</url>
</app>
<app>
<title>Cucumber</title>
<url>www.cucumber.com</url>
</app>
</directory>
Assuming I had been able to read it and store the content as a string:
s = '<directory><app><title>Carrot</title><url>www.google.com</url></app><app><title>Cucumber</title><url>www.cucumber.com</url></app></directory>';
How do I convert it to a JavaScript object like the following?
{
"directory": {
"app": [
{ "title": "Carrot", "url": "www.carrot.com" },
{ "title": "Cucumber", "url": "www.cucumber.com" }
]
}
}
I use this plugin ... http://www.thomasfrank.se/xml_to_json.html
Its always worked a charm for me.
I think you are looking for the answer to the following question Convert XML to JSON (and back) using Javascript
XML <-> JSON conversion in Javascript
quoted answer
I think this is the best one: Converting between XML and JSON
Be sure to read the accompanying article on the Xml.com O'Reilly site (linked to at the >bottom). The writer goes into details of the problems with these conversions, which I think >you will find enlightening. The fact that O'Reilly is hosting the article should indicate >that Stefan's solution has merit.
I'm writing a simple web service that return a JSON response. It'll be heavily used, so I want to try and make the JSON response as small as possible for performance reasons. I'm on the fence over a design decision; penny for your thoughts!
My JSON response from the server looks like this:
{
"customers":
[
{
"id": "337",
"key": "APIfe45904c"
},
{
"id": "338",
"key": "somethingDifferent"
},
{
"id": "339",
"key": "APIfe45904c"
},
{
"id": "340",
"key": "APIfe45904c"
}
]
}
The APIfe45904c here is used in about 60-70% of the records, so I could also modify the the JSON response to remove the repeated information and add a default_key i.e. if there's no key specified, the client should assume the default_key like this:
{
"default_key": "APIfe45904c",
"customers":
[
{
"id": "337"
},
{
"id": "338",
"key": "somethingDifferent"
},
{
"id": "339"
},
{
"id": "340"
}
]
}
No client is using the web service yet, so this wouldn't break anything. Is this good practice? It works, and makes for a small JSON response, but I'm conflicted. I like the KISS principle for developers using the service, but I also want as small a JSON response as possible.
I was tempted to replace customers with c, id with i and key with k to aid reducing the file size, but I figured this will be a problem if I want to get other clients to start using it. Should I drop the idea of default_key for the same reason?
Each JSON response will likely be no more 200 lines of id/key pairs, so I don't need to incorporate pagination, etc.
I would keep it simple as you say, and then use gzip to compress it. It should compress very well as it is repetitive, and remains convenient for programmers.
See here for pointers in outputting gzip headers for AJAX: Is gzip encoding compatible with JSON?
Unless you have very special performance needs, I would always choose clarity over brevity. Especially for an API that is going to be used by many developers.
You should use the consistent format where each record has an id and a key field. What you lose in bandwidth you gain from not having to pre-process the JSON on the client-side.
I tend to analyze my JSON data structure like you but in the end it isn't worth the tiny bit of space you save. Your JSON data structure looks good... have you seen Twitter's JSON data structure? Now that is ugly.
I would go with the default key idea, but I wouldn't go as far as shortening the attribute names since that can be confusing. Perhaps you can take an argument from the web service call (from query string) that specifies whether or not the client desires to have shortened attribute names.