-1

Json:

{
  "Herausgeber": "Xema",
  "Nummer": "1234-5678-9012-3456",
  "Deckung": 2e+6,
  "Waehrung": "EURO",
  "Inhaber": {
    "Name": "Mustermann",
    "Vorname": "Max",
    "maennlich": true,
    "Hobbys": [ "Reiten", "Golfen", "Lesen" ],
    "Alter": 42,
    "Kinder": [],
    "Partner": null
  }
}

Is there a quick way to evaluate this like in javascript, so you can have a python 2.7 object by simple evaluating a full textfile in JSON-Format?

So you have something like:

file = read('text.json')
obj = eval(file)
peter
  • 315
  • 1
  • 3
  • 11
  • possible duplicate of [Parsing values from a JSON file in Python](http://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file-in-python) – tgrosinger Jan 29 '15 at 17:38

2 Answers2

4

Don't eval(); JSON is not Python even if they look a lot alike. Use the json module to parse it:

import json

with open('text.json') as f:
    obj = json.load(f)

This uses json.load() to load the JSON data from an open file object. If you have a string containing the JSON data use json.loads() (note the s).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

You can try:

eval("""{
  "Herausgeber": "Xema",
  "Nummer": "1234-5678-9012-3456",
  "Deckung": 2e+6,
  "Waehrung": "EURO",
  "Inhaber": {
    "Name": "Mustermann",
    "Vorname": "Max",
    "maennlich": true,
    "Hobbys": [ "Reiten", "Golfen", "Lesen" ],
    "Alter": 42,
    "Kinder": [],
    "Partner": null
  }
}""")

The above code raised an error:

NameError: name 'true' is not defined

So, because the true keyword is not acceptable in python, you'd better not to do this.


Do this istead:

import json

obj = json.loads("""{
      "Herausgeber": "Xema",
      "Nummer": "1234-5678-9012-3456",
      "Deckung": 2e+6,
      "Waehrung": "EURO",
      "Inhaber": {
        "Name": "Mustermann",
        "Vorname": "Max",
        "maennlich": true,
        "Hobbys": [ "Reiten", "Golfen", "Lesen" ],
        "Alter": 42,
        "Kinder": [],
        "Partner": null
      }
    }""")

print(obj)
Alfred Huang
  • 17,654
  • 32
  • 118
  • 189
  • 1
    The "you can try" part is bad advice, and not just because "true" isn't accepted by python. This data is not python, treating it as such is a coding error. It's no different than if you tried to call `eval` on XML or a recipe or song lyrics. – Bryan Oakley Jan 29 '15 at 17:49