-3

NOTE:- I am just beginning with JSON with javascript and was trying this simple script. I want to make use of JSON.parse() here to fetch the data

Here is a snippet of my code

<html>

<body>
  <div id="output"></div>
</body>
<script>
  var text = "'college':{'stream':{'commerce':{'junior':['FY','SY'],'bachelor':['Bcom','BMM']},'science':{'junior':['FY','SY'],'bachelor':['Bsc','BTech']},'arts':{'junior':['FY','SY'],'bachelor':['BA','B.Ed']},}}";
  var jcontent = JSON.parse(text);
  document.getElementById('output').innerHTML += jcontent;
</script>

</html>

Nothing is getting displayed. I don't understand what is the problem. Can anyone help? Edit- I corrected the string which spanned multiple lines but it still doesn't work

Harsh
  • 372
  • 2
  • 15
  • 1
    Newlines are not allowed in JavaScript strings unless you are using template strings with backticks – Explosion Pills Nov 15 '17 at 18:29
  • 4
    Possible duplicate of [Parsing string as JSON with single quotes?](https://stackoverflow.com/questions/36038454/parsing-string-as-json-with-single-quotes) – Bustikiller Nov 15 '17 at 18:29
  • 3
    (1) You cannot have a string literal span multiple lines. It's a syntax error. Use your browser's developer tools. (2) Even if you could have new lines, the content of the your string is not valid JSON. (3) There is no reason to define JSON inside a JavaScript file. Just create an object via an object literal. (4) Even if parsing the JSON would work, `document.getElementById('output').innerHTML += jcontent;` wouldn't give you any useful result because you are converting an object to a string. – Felix Kling Nov 15 '17 at 18:29
  • 2
    Is there any reason why you don't just use `jcontent = {'college':{ .... }}`? JSON is a _Javascript serialized object_ so it'll easily be parsed in pure javascript. – h2ooooooo Nov 15 '17 at 18:30
  • 2
    @h2ooooooo: An object literal is not JSON however. Saying "so it'll easily be parsed in pure javascript" is misleading without context. – Felix Kling Nov 15 '17 at 18:32
  • Paste your JSON into this and follow the errors https://jsonlint.com/ – msanford Nov 15 '17 at 18:32
  • @FelixKling Any JSON should be unserializeable in javascript, no? Is there any part of the notation that allows objects that javascript doesn't? – h2ooooooo Nov 15 '17 at 18:33
  • All I am saying is that `jcontent = {'college':{ .... }}` is not JSON. Maybe I misunderstood your comment. – Felix Kling Nov 15 '17 at 18:33
  • 1
    @FelixKling Maybe we simply misunderstood each other. I was simply trying to use language that OP might be able to understand better as I strongly believe this is either a completely different problem all together or an XY problem. What I meant is a simple "_this looks like a regular javascript object rather than any JSON and you can probably just remove the quotes_" – h2ooooooo Nov 15 '17 at 18:35

2 Answers2

2

There are many problems with this snippit.

  • JavaScript doesn't tolerate newlines within "", you must use a template string within ``.
  • The JSON string you provide is not valid JSON: it uses single quotes, and it needs an extra object wrapper {}. When in doubt, hit https://jsonlint.com/ and see if it parses.
  • You are prasing the string, which returns an object, and attempting to print that into a web page. That will produce the string representation of an object, which is [Object object], which is rather useless.
  • So you need to stringify the object to see it, which is where you started...

var text = `
{
    "college": {
        "stream": {
            "commerce": {
                "junior": ["FY", "SY"],
                "bachelor": ["Bcom", "BMM"]
            },
            "science": {
                "junior": ["FY", "SY"],
                "bachelor": ["Bsc", "BTech"]
            },
            "arts": {
                "junior": ["FY", "SY"],
                "bachelor": ["BA", "B.Ed"]
            }
        }
    }
}`;
var jcontent = JSON.parse(text);
// JSON.parse() returns an object, whose string representation is
// "[Object object]", so you actually want to JSON.stringify() this to see it

document.getElementById('output').innerHTML += jcontent;
document.getElementById('output2').innerHTML += JSON.stringify(jcontent, 0, 2);
document.getElementById('output3').innerHTML += JSON.stringify(jcontent['college']['stream']['arts']['junior'], 0, 2);
<html>

<body>
  Original output:
  <pre id="output"></pre>

  Junior arts?
  <pre id="output3"></pre>

  Whole thing:
  <pre id="output2"></pre>
</body>

</html>
msanford
  • 11,803
  • 11
  • 66
  • 93
  • i will run a loop to get the actual value from the JSON object. But the real problem is that the objects are not even retreived. The script you provided displays this --- var text = ` {"college": { "stream": { "commerce": { "junior": ["FY", "SY"], "bachelor": ["Bcom", "BMM"] }, "science": { "junior": ["FY", "SY"], "bachelor": ["Bsc", "BTech"] }, "arts": { "junior": ["FY", "SY"], "bachelor": ["BA", "B.Ed"] } } }} `; var jcontent = JSON.parse(text); document.getElementById('output').innerHTML += jcontent; document.getElementById('output2').innerHTML += JSON.stringify(jcontent, 0, 2); – Harsh Nov 15 '17 at 18:51
  • 1
    @Harsh I know what my script displays, just hit Run. To the first part of your comment, I don't understand what you mean. What _do you expect to see?_ – msanford Nov 15 '17 at 18:52
  • 1
    Note that "JSON Object" doesn't make sense (though it is commonly said): JSON is _a string_ which needs to be _parsed into an object_ for you to retrieve vales. Do you want to iterate over the object? – msanford Nov 15 '17 at 18:53
  • IF you mean that your original string doesn't parse into an object: no, it won't, because it is not valid JSON as everyone has said. Very carefully read the way the JSON string above is constructed and compare it to what you have in your example, as well as the bullet ppoints I outlined. You need to wrap your string in an extra pair of `{}` and then `JSON.parse()` that. Once you have that, just access it as any other object. I'll update with an example. – msanford Nov 15 '17 at 18:56
  • No problem. I updated with another example accessing it. – msanford Nov 15 '17 at 18:58
0

Your json format is invalid. You shouldn't use multilines in javascript strings and quotes must be converted to double quotes. Like this;

var text = '{"college":{"stream":{"commerce":{"junior":["FY","SY"],"bachelor":["Bcom","BMM"]},"science":{"junior":["FY","SY"],"bachelor":["Bsc","BTech"]},"arts":{"junior":["FY","SY"],"bachelor":["BA","B.Ed"]}}}}';
JSON.parse(text);

Also you can validate your json using online Json validator websites. Like this.

lucky
  • 12,734
  • 4
  • 24
  • 46
  • This adds nothing to the existing answer, nor does it address the other problems with the code OP presented. – msanford Nov 15 '17 at 18:50