• 0

Parsing JSON in Javascript


Go to solution Solved by virtorio,

Question

andrew.p.shay

Hello all,
I am new to Javascript and I am trying to parse the following JSON. But nothing happens so I'm assuming there is some error.

I am also trying to figure out how to loop through the JSON and access the data, but I can't even get it to load.

var text = [
    {"ITEM ONE":[
            {"SUB ONE":[
                    "one",
                    "two"
                ]
            },
            {"SUB TWO":[
                    "three",
                    "four"
                ]
            }

    ]},


    {"ITEM TWO":[
            {"SUB THREE":[
                    "five"
                ]
            },
            {"SUB FOUR":[
                    "six"
                ]
            }

    ]}
];

var obj = JSONArray.parse(text);
JSONObject jo = inputArray.getJSONObject(0);
document.getElementById("demo").innerHTML = obj(0);

Here are the variations that I've tried. For var obj, I tried using just JSON.parse(). I also tried not have the jo var.

 

And for the JSON itself, I also tried adding the following to each line 'JSON_HERE'+  To try and deal with the multiline JSON.  I also put it all on one line.

 

I'm not sure what to do. Could someone show me the problem and some code that accesses the element and a snippet that loops through it?

Link to post
Share on other sites

2 answers to this question

Recommended Posts

  • 0
+virtorio

...

 

 

 

Couple of issues:

 

1. You're assigning a real object to "text", not actual text that needs parsing

2. JSONArray isn't a type, use JSON.parse()

3. You never define an object called "inputArray"

4. Don't provide a type when creating an variable (JSONObject jo)

 

Below is a working demo that parses your JSON (as text) and writes a value from it into a <P> tag.

 

One more thing When testing javascript it's always helpful to load up your browsers developer tools (CTRL SHIFT I in Chrome, F12 in IE) and step though and inspect your code. You can learn a lot from it. 

<!doctype html>
<html>
<head>
 
</head>
<body>
<p id="demo"></p>
 
 
<script>
var text = "[\
    {\"ITEM ONE\":[\
            {\"SUB ONE\":[\
                    \"one\",\
                    \"two\"\
                ]\
            },\
            {\"SUB TWO\":[\
                    \"three\",\
                    \"four\"\
                ]\
            }\
    ]},\
    {\"ITEM TWO\":[\
            {\"SUB THREE\":[\
                    \"five\"\
                ]\
            },\
            {\"SUB FOUR\":[\
                    \"six\"\
                ]\
            }\
    ]}\
]";
 
var obj = JSON.parse(text);
var jo = obj[0];
document.getElementById("demo").innerText = obj[0]["ITEM ONE"][0]["SUB ONE"][0];
</script>
 
</body>
</html>
Link to post
Share on other sites
  • 0
andrew.p.shay

...

 

Thank you very much!

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By News Staff
      Save 97% off this Complete One-Hour Coder Bundle - now just $34.99
      by Steven Parker

      Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where you can save 97% off this Complete One-Hour Coder Bundle. Train your inner programmer with 6 one-hour courses on C++, CSS, HTML, JavaScript, and Python.



      This bundle consists of the following courses:

      C++ Foundations
      Begin Your Coding Journey with the High-End, Popular C++ Language for Software & Game Development CSS Foundations
      Enhance Website Aesthetics & Designs with the Style Sheet Language CSS HTML Foundations
      Start Creating Your Own Websites, Web Apps, & More Java Foundations
      Master the General Purpose & Object-Oriented Language of Java for Mobile Development JavaScript Foundations
      Learn JavaScript for Web & HTML5 Game Development Python Foundations
      Learn the Foundations of Python for Data Science & Machine Learning Good to know
      Updates included Certification of completion included Length of time users can access this course: lifetime Redemption deadline: redeem your code within 30 days of purchase For specifications, license and instructor info please click here.

      Here's the deal:
      This Complete One-Hour Coder Bundle normally costs* $1,200, but it can be yours for just $34.99 for a limited time, that's a saving of $1,165.01 (97%) off.

      >> Get this deal, or learn more about it here <<
      See all Online Courses on offer. This is a time-limited offer that ends soon.
      Get $1 credit for every $25 spent · Give $10, Get $10 · 10% off for first-time buyers.

      Not for you?
      If this offer doesn't interest you, why not check out the following offers:



      The Win Your Dream 2020 Tesla Model 3 Giveaway 20% off Ivacy VPN subscription with coupon code IVACY20 NordVPN subscription at up to 68% off for a 2 year plan Private Internet Access VPN subscription at up to 71% off Unlocator VPN or SmartDNS unblock Geoblock with 7-day free trial Subscribe to Neowin for $14 a year, or $28 a year for Ad-Free experience Disable Sponsored posts · Neowin Deals · Free eBooks · Neowin Store

      Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs.

    • By News Staff
      Get this Interactive Learn to Code Bundle at 73% off for just $29.99
      by Steven Parker

      Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where you can save 73% off the Interactive Learn to Code Bundle. Start writing codes and programs from scratch with 9 interactive courses on SQL, JavaScript, PHP, jQuery, BootStrap, and more.



      This deal consists of the following courses:

      An Interactive SQL Tutorial for Beginners: Introduction to SQL
      Getting Started with SQL Doesn't Have to Be Hard An Interactive JavaScript Course for Beginners
      Learn JavaScript Interactively with a One-of-a-Kind JS Online Course Interactive jQuery Tutorial: Learn jQuery Step-by-Step
      Take an Interactive jQuery Training Course for Beginners to Quickly Master jQuery Events, Effects & More Learn PHP Online: PHP Basics Explained in an Interactive & Fun Manner
      An Interactive Tutorial for Beginners Who Want to Master PHP Basics in a Non-Boring Way The Complete Solidity Smart Contract Guide
      Master Solidity Programming Through Hands-On Experience Master Python Fundamentals the Fun Way: An Interactive Python Tutorial
      A Python Training Course for Absolute Beginners Who Wants to Master the Language Without Getting Bored A Responsive Web Design Course: Find Out How to Create a Responsive Website
      Make a Website Mobile-Friendly with a Step by Step, Responsive Web Design Tutorial Bootstrap Tutorial: Learn to Create Dynamic Websites in a Pinch
      Find Out How to Use Bootstrap the Fun Way by Using an Interactive Course An Interactive Java Tutorial: Learn by Practice!
      Learn Java From Scratch by Combining Theory with Hands-On Coding Experience Good to know
      Length of time users can access this course: lifetime Certification of completion included Redemption deadline: redeem your code within 30 days of purchase For a full description, specs, and instructor info, click here.

      Here's the deal:
      This Interactive Learn to Code Bundle normally costs* $112, but you can pick it up for just $29.99 for a limited time - that represents a saving of $82.01 (73%) off.

      >> Get this deal, or learn more about it <<
      See all discounted Online Courses. This is a time-limited offer.


      Get $1 credit for every $25 spent · Give $10, Get $10 · 10% off for first-time buyers.

      Not for you?
      If this offer doesn't interest you, why not check out the following offers:

      The Win Your Dream 2020 Tesla Model 3 Giveaway
      The Nintendo Gaming Bundle Giveaway 20% off Ivacy VPN subscription with coupon code IVACY20 NordVPN subscription at up to 68% off for a 2 year plan Private Internet Access VPN subscription at up to 71% off Unlocator VPN or SmartDNS unblock Geoblock with 7-day free trial Disable Sponsored posts · Other recent deals · Preferred partner software

      Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs.

      running costs.

    • By News Staff
      Free eBook: Your First Week With Node.js
      by Steven Parker

      Claim your complimentary copy for free, before the offer expires.



      What's it about?


      A beginner's introduction to Node and its related technologies.

      Used by some of the biggest companies today, Node is blazingly fast. Taking JavaScript, a ubiquitous language among developers, we'll get you up and running with guides on when to use Node, NPM, Security, as well as connecting with MySQL, MongoDB and more.

      How to get it
      Please ensure you read the terms and conditions to claim this offer. Complete and verifiable information is required in order to receive this free offer. If you have previously made use of these free offers, you will not need to re-register. While supplies last!

      >> Your First Week With Node.js - free eBook <<
      Offered by SitePoint, view their other free resources. Limited time offer.

      Not for you?
      That's OK, there are other free eBooks on offer you can check out here, but be aware that these are all time-limited offers. If you are uncomfortable sharing your details with a third-party sponsor, we understand. Or via our preferred partner:

      How can I disable these posts? Click here.

      Disclosure: A valid email address is required to fulfill your request. Complete and verifiable information is required in order to receive this offer. By submitting a request, your information is subject to TradePub.com's Privacy Policy.

    • By News Staff
      Build Your First Node App - free eBook
      by Steven Parker

      Claim your complimentary copy for free, before the offer expires.



      What's it about?


      Bring to life your own Node app.

      A practical walkthrough of building an app server side with JavaScript (Node.js). Starting with Node.js use cases, then defining routes, synchronising the database and finally serving files.

      How to get it
      Please ensure you read the terms and conditions to claim this offer. Complete and verifiable information is required in order to receive this free offer. If you have previously made use of these free offers, you will not need to re-register. While supplies last!

      >> Build Your First Node App - free eBook <<
      Offered by SitePoint, view their other free resources. Limited time offer.

      Not for you?
      That's OK, there are other free eBooks on offer you can check out here, but be aware that these are all time-limited offers. If you are uncomfortable sharing your details with a third-party sponsor, we understand. Or via our preferred partner:

      How can I disable these posts? Click here.

      Disclosure: A valid email address is required to fulfill your request. Complete and verifiable information is required in order to receive this offer. By submitting a request, your information is subject to TradePub.com's Privacy Policy.

    • By News Staff
      Save 73% off the Interactive Learn to Code Bundle - now just $29.99
      by Steven Parker

      Today's highlighted deal comes via our Online Courses section of the Neowin Deals store, where you can save 73% off the Interactive Learn to Code Bundle. Start writing codes and programs from scratch with 9 interactive courses on SQL, JavaScript, PHP, jQuery, BootStrap, and more.



      This deal consists of the following courses:

      An Interactive SQL Tutorial for Beginners: Introduction to SQL
      Getting Started with SQL Doesn't Have to Be Hard An Interactive JavaScript Course for Beginners
      Learn JavaScript Interactively with a One-of-a-Kind JS Online Course Interactive jQuery Tutorial: Learn jQuery Step-by-Step
      Take an Interactive jQuery Training Course for Beginners to Quickly Master jQuery Events, Effects & More Learn PHP Online: PHP Basics Explained in an Interactive & Fun Manner
      An Interactive Tutorial for Beginners Who Want to Master PHP Basics in a Non-Boring Way The Complete Solidity Smart Contract Guide
      Master Solidity Programming Through Hands-On Experience Master Python Fundamentals the Fun Way: An Interactive Python Tutorial
      A Python Training Course for Absolute Beginners Who Wants to Master the Language Without Getting Bored A Responsive Web Design Course: Find Out How to Create a Responsive Website
      Make a Website Mobile-Friendly with a Step by Step, Responsive Web Design Tutorial Bootstrap Tutorial: Learn to Create Dynamic Websites in a Pinch
      Find Out How to Use Bootstrap the Fun Way by Using an Interactive Course An Interactive Java Tutorial: Learn by Practice!
      Learn Java From Scratch by Combining Theory with Hands-On Coding Experience Good to know
      Length of time users can access this course: lifetime Certification of completion included Redemption deadline: redeem your code within 30 days of purchase For a full description, specs, and instructor info, click here.

      Here's the deal:
      This Interactive Learn to Code Bundle normally costs* $112, but you can pick it up for just $29.99 for a limited time - that represents a saving of $82.01 (73%) off.

      >> Get this deal, or learn more about it <<
      See all discounted Online Courses. This is a time-limited offer.
      Get $1 credit for every $25 spent · Give $10, Get $10 · 10% off for first-time buyers.

      Not for you?
      If this offer doesn't interest you, why not check out the following offers:

      The Nintendo Gaming Bundle Giveaway 20% off Ivacy VPN subscription with coupon code IVACY20 NordVPN subscription at up to 68% off for a 2 year plan Private Internet Access VPN subscription at up to 71% off Unlocator VPN or SmartDNS unblock Geoblock with 7-day free trial Disable Sponsored posts · Other recent deals · Preferred partner software

      Disclosure: This is a StackCommerce deal or giveaway in partnership with Neowin; an account at StackCommerce is required to participate in any deals or giveaways. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through our branded deals site, and it all goes toward the running costs.