javascript (no jquery) - load a local json file - javascript

I have a local JSON file which I converted into a JS object by adding var data = ... in front of that:
var data = {
"people": [
{
"name": "Martin",
"surname": "Smith"
},
{
"name": "Jack",
"surname": "Smith"
}
]
}
I load it with: <script src="data.json" type="text/javascript"> and try to parse it with:
var h = JSON.parse(data);
I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

When you put var data = { in front of it, it stops being JSON and becomes JavaScript. (So you shouldn't give it a .json file extension and that will encourage servers to tell browsers that it is JSON and not JS).
In this case, it is a JavaScript program that assigns an object to a variable.
JSON.parse takes a string containing JSON and converts it into a JavaScript object (or array or other data type).
Don't parse it. It is already parsed by the JavaScript compiler.

Here MZN JSON.parse() you can see what JSON.parse() should be used for. It is used on a String that contains a JSON object, and this method would parse it into the format that your data variable is already in. Since your data variable is already in JSON format, your variable is ready to use and you do not need the JSON.parse() method.

Related

JSON.parse giving only the last element as output

I am using JSON to carry information from NodeJS (server side) to my client side. When I try to parse the JSON in the client side, it outputs only the last element, in this case, 'name: "Sam"'. I want all the elements to be outputted.
I have tried using an array and a variable to be assigned the parsed data. I have also directly tried logging it to the console with: [console.log(JSON.parse(this.response));]. All three gave the same result.
The first console.log returns all the elements in JSON form. The second one returns only the last one. There are 3 elements in total.
I expect all the elements to be assigned to the variable.
request.open('GET', 'http://localhost:3000/listofvoted', true);
request.onload = function () {
console.log(this.response)
console.log(JSON.parse(this.response));
}
request.send();
The JSON I receive:
{
"name": "Bran",
"name": "Ram",
"name": "Sam"
}
Although JSON (which is just a notation) allows for duplicate key names, the guidance is that that they SHOULD be unique. If you want to use JSON to create a JavaScript Object, then you are constrained by the fact that a JavaScript Object cannot have duplicate keys. So although you have valid JSON, it cannot be represented by a JavaScript Object and therefore it will not survive a round trip of being parsed (JSON converted to a JavaScript Object) by JSON.parse and then converted back to JSON.
For your own convenience of working in JavaScript, you could consider changing the JSON representation of your information so that it can be represented as a JavaScript Object.
Here are some alternative ways of representing what you have that may work:
Use an array of discrete objects:
[
{ "name": "Bran" },
{ "name": "Ram" },
{ "name": "Sam }"
]
Use an array of names:
{
"names": [ "Bran", "Ram", "Sam" ]
}
As a final, heavy-handed approach, you don't have to convert your JSON to a JavaScript object. You can parse it using a parser that allows you to provide your own handlers for the syntactic elements that occur in the JSON string and you can handle the duplicate keys in whatever way you wish. May I suggest the clarinet library for doing so.
See also, How to get the JSON with duplicate keys completely in javascript

parsing multidimensional javascript json array with php

I have the following multidimensional javascript array:
My js array
and I want to parse it and return some values from it (name and url)
but when cleaning it up a bit $jsonData = str_replace('var stations = ','' ,$jsonDataUrl); and trying to parse it as json with json_decode($jsongoeshere), the parser returned error 4 even if this URL had told me
that The JSON input is valid in JavaScript.
So now I am a bit lost on how to parse it.
quoted object property name expected is your error.
Your JSON string is not valid, object property names must be quoted.
This
{
"aland": [
{
name: "Ålands Radio",
logo: "stations/images-europe/aland/Ålands Radio.png",
url: "http://194.110.182.131:8000/stream.ogg"
},
...
Should be
{
"aland": [
{
"name": "Ålands Radio",
"logo": "stations/images-europe/aland/Ålands Radio.png",
"url": "http://194.110.182.131:8000/stream.ogg"
},
...
These JSON validators give you the correct error.
https://jsonlint.com/ & https://jsonformatter.curiousconcept.com/
Also, what #JJAulde said is true.
You have a semicolon at the end of your JSON string that will cause the parse to fail. You need to rtrim or str_replace it like you did with var stations =

Using Json data as function parameter

I've been recently trying a develop a simple application, which would use user input, convert it to json and use that json in another function to draw graph. I managed to output correct json to console, but when I try to call it as a parameter in the function which uses it to draw graph, it fails to work. If I manually copy console output directly to the plotting function it works normally. So the question here is, how does one use Json as a function parameter.
graph obj:
var graph = {
"nodes": [],
"edges": []
}
..some code which fills graph (irrelevant here).. ending with a function call:
console.log(JSON.stringify(graph, null, '\t')); //works perfectly if manually copied
var inpt = JSON.stringify(graph, null, '\t');
execute(inpt); //doesn't work
And the execute() with the json line:
execute(input)
elements: input,
...some more code...
Don't pass the JSON string. Instead pass the graph object directly. The JSON (JavaScript Object Notation) format is native for JavaScript. The JSON string representation is used to transfer the object to environments that does not support it directly, for example consuming a JSON object in a service written in C# or Java.
When an object in JavaScript var o = { field: "value" }; is passed as an argument to a function function f(p) {...}, then in the function the field can be accessed directly p.field....
When the object is needed outside the JavaScript scope, then it should be serialized to a JSON string { "field": "value" }. The recepient can retrieve the field and the value from the string following the JSON construction convention. JSON.stringify is used for object serialization.

How can I get a specific value from a JSON URL, and pass it into a Javascript variable?

I want to use a JSON URL to get up-to-date exchange rates for use in a webpage. For this I want to be able to get a specific exchange rate (say, US Dollar) and pass the rate onto a variable so I can use it in a JS function.
Here is a sample of the JSON code:
"rates": {
"AED": 3.672796,
"AFN": 57.951451,
"ALL": 112.589601,
"AMD": 430.416,
"ANG": 1.787,
"AOA": 100.82775,
"ARS": 8.52454,
"AUD": 1.175504,
"AWG": 1.79,
"AZN": 0.784233,
"BAM": 1.571689,
"BBD": 2
Assign the JSON code to a variable, e.g.var json = "{your json string}" then parse it with var obj = JSON.parse( json );. Now you can access the elements from obj.
Use JSON.stringify to turn a JavaScript variable into a JSON string and JSON.parse to do the opposite. Then you can access properties directly (obj.SomeProperty) or dynamically (obj["SomeProperty"].

How to use the json?

I have called an api using href from the html form and it in response gives json as output.
consider this as the json the api gives
{
"entry":
{
"id": "1",
"name": "SA"
}
}
I want the values of the id and name.
How can i get the values specifically and store those values to a variable.
Also i got to do this in the html form with javascript.
I want the values of the city_id and city_name. How can i get the
values specifically and store those values to a variable
Use JSON.parse to convert it to JS object and get your values:
var obj = JSON.parse(yourJSON);
var city_id = obj['entry']['city_id'];
var city_name = obj['entry']['city_name'];
Docs:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse
var a;
eval('a={"entry":{"#collection_url":"http://api.storageroomapp.com/accounts/4fe004c598f46026cc000002/collections/4fe0063798f4602e2c000016","#created_at": "2012-06-21T09:12:40Z","#trash": false,"#type": "City","#updated_at": "2012-06-21T09:12:40Z","#url":"http://api.storageroomapp.com/accounts/4fe004c598f46026cc000002/collections/4fe0063798f460e2c000016/entries/4fe2e58898f4604757000006","#version": 1,"city_id": "City_001","city_name": "London"}}');
in other words
eval ('a={/*response object*/}')
now you have (a) as object that contains your data you can access them whether like object notation (a.entry) or as an array (a['entry'])
you can also use json parse but its not compatible with all browsers
Either the eval() function or the JSON parser will allow you to create an object from the JSON and then access the fields normally. The JSON parser is a little more secure, as explained in this tutorial:
http://www.w3schools.com/json/json_eval.asp

Categories

Resources