-2

I'm trying to extract a json. I'm having wrong extracted data for "error". When I try to do with t3 = temp['errors'][0] I'm getting only "Arg one must not be null or empty."

Expected output:

"Arg one must not be null or empty.",
"Arg two must not be null or empty."

Here is my json:

{
        "status": "Fail",
        "warnings": {
            "Code": "VALID",
            "Desc": "Invalid data",
            "errors": [
                "Arg one must not be null or empty.",
                "Arg two must not be null or empty."

            ]
        }
    }

Here is my code:

tmp = json.loads(res.content)
print(tmp['status'])
temp = (tmp['warnings'])
t1 = temp['errorCode']
t2 = temp['errorDesc']
t3 = temp['errors'][0]
print(t1)
print(t2)
print(t3)

Someone Please correct me what am I doing wrong?

nancy
  • 89
  • 1
  • 1
  • 9
  • 3
    If you want both, why are you indexing with `[0]` at the end? That gets only the first from `errors`. – Carcigenicate Dec 05 '19 at 01:06
  • @Carcigenicate if I keep t3 = temp['errors'] then i'm getting [ "Arg one must not be null or empty.", "Arg two must not be null or empty." ] and I don't want [ ] brackets. – nancy Dec 05 '19 at 01:08
  • 2
    That's not "nested JSON". Its' just JSON. – ChrisGPT was on strike Dec 05 '19 at 01:09
  • 2
    Then use `', '.join` or something on the resulting list. The brackets are just part of the representation of the list. They aren't data. You only need to worry about them when printing data out. – Carcigenicate Dec 05 '19 at 01:09
  • 1
    Does this answer your question? [How to parse data in JSON?](https://stackoverflow.com/questions/7771011/how-to-parse-data-in-json) – ChrisGPT was on strike Dec 05 '19 at 01:13
  • You can just loop through the indexing of errors. – Marios Keri Dec 05 '19 at 01:21
  • @nancy Be careful, I **strongly recommend** making sure that you understand things clearly. The brackets are not just some random visual thing, they indicate a type. – AMC Dec 05 '19 at 02:52

1 Answers1

1

try just:

t3 = temp['errors']
t3
# ['Arg one must not be null or empty.', 
# 'Arg two must not be null or empty.']

you get the brackets because it's a list, if you want to concatenate the two into a string you can do this:

', '.join( temp['errors'] )
# 'Arg one must not be null or empty., Arg two must not be null or empty.'

that will create a string of the contents, without the brackets

AMC
  • 2,642
  • 7
  • 13
  • 35
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24