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.
Related
I've been trying to load certain Json with Ajax GET request and then parsing it.
However when trying to access the Json key from HTML script tag it was undefined.
In order to debug this issue, I logged all the keys of Json in console as well as the Json itself. Therefore i utilized this function:
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, "); // Explanation is below
console.log(invList[0]) // Just testing with first object
console.log(Object.keys(invList[0]));
});
}
getInv();
Purpose of data.split(",, "):
Since my backend script uses different programming language, I had to interpret it to the one suitable for Javascript.
There also were multiple Json objects, So i separated them with ",, " and then split them in Javascript in order to create a list of Json objects.
After calling the function, Following output was present:
Although the interesting part is that after pasting Json object in console like this:
This was the output:
So basically, in script tag, i was unable to access object's keys, although once i used it manually in console, all keys could be accessed.
What could be the purpose behind this? It seems quite strange that different outputs are given. Perhaps invList[0] is not Json object at all in the script tag? Thanks!
data.split() returns an array of strings, not objects. You need to use JSON.parse() to parse the JSON string to the corresponding objects.
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, ");
console.log(invList[0]) // Just testing with first object
var obj = JSON.parse(invList[0]);
console.log(Object.keys(obj));
});
}
You can use .map() to parse all of them, then you'll get an array of objects like you were expecting:
var invList = data.split(",, ").map(JSON.parse);
I am working on a parser for a text file. I am trying to parse some JSON strings into objects so I can easily display some different values on a webapp page (using flask). I am passing the strings into my html page using jinja2, and trying to parse them objects in javascript.
function parseLine(x) {
var obj = JSON.parse(x);
document.write(obj.timestamp1);
}
I am getting this error:
SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data
in the console browser. I have found many stackoverflow questions with that error, but the suggestions do not fix my problem.
If I use a dummy string, surrounded by single quotes: '{"test": "1234"}' it works fine.
If I need to include anymore information I can.
Had similar issues but was able to solve it using this way using the
reviver parameter on JSON.parse()
var Person = {}
// an empty person object
//sample json object, can also be from a server
var sampleJson = {'name': 'Peter', 'age': "20"};
//use the javascript Object.assign method to transfer the json from the source[JSON.parse]to the target[Person]
// the source is JSON.parse which take a string argument and a function reviver for the key value pair
Object.assign(Person, JSON.parse(JSON.stringify(sampleJson),
function (k, v) {
//we return the key value pair for the json
return k, v
}
)
)
console.log(Person.name) //Peter
console.log(Person.age) // age
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.
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"].
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