1

I'm very new to python.

I'm forming a json string taking input from various REST calls.

Something like:

{
   "-gammaid#10191-":{
      "domain":"Kids Interest",
      "product":"Project1"
   },
   "-gammaid#10382-":{
      "domain":"Weekend Classes",
      "product":"Project2"
   },
   "-gammaid#10442-":{
      "domain":"Knowledge Driven",
      "product":"Project3"
   },
   "-gammaid#10620-":{
      "domain":"Primary Education",
      "product":"Project4"
   },
   "-gammaid#10986-":{
      "domain":"Other Domain",
      "product":"Project5"
   },
   "-gammaid#10987-":{
      "domain":"Kids Interest",
      "product":"Project6"
   },
   "-gammaid#10996-":{
      "domain":"External Classes",
      "product":"Project7"
   },
   "-gammaid#11663-":{
      "domain":"Parent Interaction",
      "product":"Project8"
   }
}

As you see each key gammaid has in-turn a json structured value.

When I'm running my_json.get("-gammaid#11663-"), I'm getting

AttributeError: 'str' object has no attribute 'get'
reiley
  • 3,759
  • 12
  • 58
  • 114
  • 1
    your `my_json` is recognised as a string, whereas you probably want it to be interpreted as a dictionary. the answer to this question is probably what you are looking for: https://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary – KenHBS May 12 '19 at 11:04
  • What does `type(my_json)` give you @reiley ? – Devesh Kumar Singh May 12 '19 at 11:05
  • @KenHBS, thanks. Great insight. – reiley May 13 '19 at 11:45

3 Answers3

3

You need to parse it into a dictionary first:

import json

s = 'YOUR JSON STRING'

d = json.loads(s)
print(d["-gammaid#11663-"])
AdamGold
  • 4,941
  • 4
  • 29
  • 47
0

If you define it like this:

s={
   "-gammaid#10191-":{
      "domain":"Kids Interest",
      "product":"Project1"
   },
   "-gammaid#10382-":{
      "domain":"Weekend Classes",
      "product":"Project2"
   }

This is python dict. So you can just access values like this:

s["-gammaid#11663-"]
{'domain': 'Parent Interaction', 'product': 'Project8'}

If you need to actually get json object you can do it like this:

import json
json.loads(json.dumps(s))
Klemen Koleša
  • 446
  • 3
  • 6
0

Be careful, there are two function in json lib: json.load**s**() and json.load();

json.load(fs) >> takes file like object 
json.loads(str) >> takes string 

A nice way to remember it is by the extra s means string.

Markus
  • 3
  • 2