1

My JSON array is as follows and I would like to build a new string that would output accordingly.

I have a simple function just to see if I can return a value but it's failing with Error was expected string or buffer

def blah(myjson):
    data = json.loads(myjson)
    for item in data:
        result = item['svn_tag']

    return result

JSON:

[{'svn_tag': '20150623r3', 'module': 'api'}, {'svn_tag': '20150624r1', 'module': 'ui'}]

Proposed Output:

api - 20150623r3, ui - 20150623r3
4
  • Single quotes are not valid JSON. You have to use double-quotes. Commented Jul 29, 2015 at 20:57
  • Fixed thx for catching that. It was correct in my codebase. Commented Jul 29, 2015 at 20:57
  • well the interesting thing is that Ansible is returning it w/ single quotes. My JSON in the source file has double quotes but when I return the variable it converts everything to single quotes. Commented Jul 29, 2015 at 20:59
  • I take it back it is double quotes, the output is just in single quote. Commented Jul 29, 2015 at 21:01

1 Answer 1

1

The problem is that json wants the strings and field names encoded in double quotes and not single quotes. So either replace manually the single quotes or use ast.literal_eval since the string is also a python valid literal:

import ast

def blah(myjson):
    data = ast.literal_eval(myjson)
    return ', '.join(item['module'] + ' - ' + item['svn_tag'] for item in data)

s = '''[{'svn_tag': '20150623r3', 'module': 'api'}, {'svn_tag': '20150624r1', 'module': 'ui'}]'''
print blah(s)

Result:

api - 20150623r3, ui - 20150624r1
Sign up to request clarification or add additional context in comments.

8 Comments

grrrr so it's telling me there's a Keyerror for module and svn_tag. return ', '.join(item['svn_tag'] for item in data) KeyError: 'svn_tag
Do you use the same string? Otherwise check if svn_tag is defined for each array entry.
i think it's an Ansible thing so ignore the Keyerror. So I'm pretty sure the string/variable that I'm passing in is this [{'svn_tag': '20150624r1_6.36_gameofthrones', 'module': 'ariaapi'}] because if I return the variable that i passed to the function that's what gets displayed. However, running it through the function you have, it's throwing a ValueError: malformed string
This is because the variable isn't a string but an already python array. So skip the whole parsing thing and use ', '.join(item['module'] + ' - ' + item['svn_tag'] for item in variable_name)
Ughhh ... so w/o the data = ast.literal_eval(myjson) line and with only return ', '.join(item['module'] + ' - ' + item['svn_tag'] for item in myjson) yields KeyError: 'module'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.