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
Related
I've a table in a SQL DB in which I store a JavaScript object like this:
{content: ['First paragraph','second paragraph']}
I get it from DB and try to pass to a function which needs an object formatted like it:
this._schedaService.getObjectFromDBToPrintPdf().subscribe(data => {
pdfMake.createPdf(data).download('tempPdf.pdf');
});
The problem is that data is always a string.
I've tried JSON.parse(data) but (obviously) doesn't work.
If I write
cont temp = {content: ['First paragraph','second paragraph']};
it works.
Does anyone have a good idea?
If you use the JSON.parse JavaScript function, e.g.
var data = JSON.parse("{content: ['First paragraph','second paragraph']}");
you will receive the following error:
Uncaught SyntaxError: Unexpected token c in JSON at position 1
because your input string does not have a valid JSON object syntax.
Your input string should have this format:
'{"content": ["First paragraph","second paragraph"]}'
I solved it in a tricky way: since JSON.parse is a specific type of the eval function, I just focused on JSON. The only solution (that I've found 'till now) is:
var str = "{content: ['First paragraph','second paragraph']}";
var obj = eval("(" + str + ")");
N.B. typeof(obj) returns
object
Here is an useful link.
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 have not worked too much on javascript. And, I need to parse a JSON string. So, I want to know what exactly JSON.parse does. For example :
If I assign a json string to a variable like this,
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now when I print 'ab', I get an object.
Similarly when I do this :
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
var rs = JSON.parse(pq);
The 'rs' is the same object as 'ab'. So what is the difference in two approaches and what does JSON.parse did differently ?
This might be a silly question. But it would be helpful if anybody can explain this.
Thanks.
A Javascript object is a data type in Javascript - it's have property and value pair as you define in your first example.
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now What is Json : A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other)
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
so it's is a String With json Format.
and at last JSON.parse() Returns the Object corresponding to the given JSON text.
Here is my explanation with a jsfiddle.
//this is already a valid javascript object
//no need for you to use JSON.parse()
var obj1 = {"name":"abcd", "details":"1234"};
console.log(obj1);
//assume you want to pass a json* in your code with an ajax request
//you will receive a string formatted like a javascript object
var str1 = '{"name":"abcd", "details":"1234"}';
console.log(str1);
//in your code you probably want to treat it as an object
//so in order to do so you will use JSON.parse(), which will
//parse the string into a javascript object
var obj2 = JSON.parse(str1);
console.log(obj2);
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
Your 'ab' variable isn't a string, it is a proper javascript object, since you used the {} around it. If you encased the whole thing in "" then it would be a string and would print out as a single line.
Data Type!! That is the answer.
In this case, ab is an object while pq is a string (vaguely speaking). Print is just an operation that displays 'anything' as a string. However, you have to look at the two differently.
String itself is an object which has properties and methods associated with it. In this case, pq is like an object which has a value: {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}} and for example, it has a property called length whose value is 66.
But ab is an object and you can look at name and details as its properties.
What JSON.parse() did differently was that, it parsed (converted) that string into an object. Not all strings can be parsed into objects. Try passing {"name":"abc" and JSON.parse will throw an exception.
Before parsing, pq did not have any property name. If you did something like pq.name, it'll return you undefined. But when you parsed it using JSON.parse() then rs.name will return the string "abcd". But rs will not have the property length anymore because it is not a string. If you tried rs.length then you'll get a value undefined.
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.
I have an array that is printed in JSON
[{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}]
For some reason, I divided the JSON into two parts.
In javascript I used JSON.parse() to decode the JSON above.
for example:
var arr = JSON.parse(response); //The response variable contains the above JSON
alert(arr[0].Name) //Still it outputs John Ranniel, but If i change the content of the alert box on the second part of the JSON,
alert(arr[1].Contact) // It has no output, I don't know if there is a problem with the index of the array.
Make sure your JSON is a string type:
'[{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Emergency Contact":"09197875656","Relation":"Sister"}]'
and then, you can use,
var arr = JSON.parse(response); //The response variable contains the above JSON
console.log(arr[0].Name);
console.log(arr[1]['Emergency Contact']); // There is no 'Contact' property iun your object, and you should use this when there's a space in the name of the property.
See:
var response = '[{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Emergency Contact":"09197875656","Relation":"Sister"}]';
var arr = JSON.parse(response);
console.log(arr[0].Name);
console.log(arr[1]['Emergency Contact']); // There is no 'Contact' property iun your object, and you should use this when there's a space in the name of the property.
You are trying to parse something which is already a JavaScript object, and does not need to be parsed. You need to parse JSON strings. This is not a JSON string. It's a JavaScript object.
Consider the following:
JSON.parse([1,2])
This will coerce the array [1,2] into the string "1,2". JSON.parse will then choke on the ,, since it doesn't belong there in a valid JSON string.
In your case the object will be coerced to the string
"[object Object],[object Object]"
JSON.parse will accept the leading [ as the beginning of the array, then throw on the following character, the o, since it does not belong there in a proper JSON string.
But you say that the JSON.parse worked and resulted in arr. In other words, the parameter you fed to JSON.parse apparently was a string, and was parsed correctly. In that case, the alerts will work fine.
Your JSON structure is array, must be parse to JSON,use JSON.stringify parse this to JSON:
var json = [{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}];
var str = JSON.stringify(json);
console.log(json);
var arr = JSON.parse(str);
alert(arr[0].Name) //Still it outputs John Ranniel, but If i change the content of the alert box on the second part of the JSON,
alert(arr[1].Contact) // It has no output, I don't know if there is a problem with the index of the array.
Demo: Link
This JSON is array, you can use directly:
var json = [{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}];
alert(json[0].Name);
alert(json[1].Contact);