tklustig
tklustig

Reputation: 503

Reading out JSON using JavaScript

given is following JSON-File:

{
   "name": "yiisoft/yii2-app-advanced",
   "description": "Yii 2 Advanced Project Template",
   "keywords": ["yii2", "framework", "advanced", "project template"],
   "homepage": "http://www.yiiframework.com/",
   "type": "project",
   "license": "BSD-3-Clause",
   "support": {
       "issues": "https://github.com/yiisoft/yii2/issues?state=open",
       "forum": "http://www.yiiframework.com/forum/",
       "wiki": "http://www.yiiframework.com/wiki/",
       "irc": "irc://irc.freenode.net/yii",
       "source": "https://github.com/yiisoft/yii2"
   },
   "minimum-stability": "dev",
   "require": {
       "php": ">=5.4.0",
       "yiisoft/yii2": "~2.0.6",
       "yiisoft/yii2-bootstrap": "~2.0.0",
       "yiisoft/yii2-swiftmailer": "~2.0.0"
   },
   "require-dev": {
       "yiisoft/yii2-debug": "~2.0.0",
       "yiisoft/yii2-gii": "~2.0.0",
       "yiisoft/yii2-faker": "~2.0.0",
       "codeception/base": "^2.2.3",
       "codeception/verify": "~0.3.1"
   },
   "config": {
       "process-timeout": 1800
   },
   "repositories": [
       {
           "type": "composer",
           "url": "https://asset-packagist.org"
       }
   ]
}

How to read out property minimum-stability? Following code fails by throwing out error:qnips_JSON_Loesung.html:112 Uncaught ReferenceError: stability is not defined

output+="<th class='spalte'>"+daten.minimum-stabilty+"</th></tr>";

By the way, following construct works quite fine:

output+="<th class='spalte'>"+daten.keywords+"</th></tr>";

Upvotes: 0

Views: 408

Answers (4)

tklustig
tklustig

Reputation: 503

Following code solved my problem:

for(let j in daten["require-dev"]){
output+="<label> Version "+daten["require-dev"][j]+"<br></label>";
}

Upvotes: 0

v.j
v.j

Reputation: 196

Using daten["minimum-stabilty"] should work fine

Other alternatives are also suggested in the older post related to this problem: Unable to access JSON property with "-" dash

Upvotes: 0

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

Here daten.minimum-stabilty is being confused with this expression (i.e. daten.minimum - stabilty). It thinks to subtract between daten.minimum and stability

To access a key that contains dash or other characters that are not permissible to be appear as an identifier, use brackets notation like this

daten["minimum-stabilty"];

Have you tried like this to access the json key that contains - ?

var json_with_dash_key = daten["minimum-stabilty"];
output+="<th class='spalte'>"+ json_with_dash_key +"</th></tr>";

Upvotes: 1

The eternal newbie
The eternal newbie

Reputation: 131

The - makes JavaScript think it's a calculation.

Either remove that when the file is created or access it like a map.

Upvotes: 1

Related Questions