0

I am reading a JSON file with data in it and I am trying to ensure that each file that is created in my code has a unique value. However sometimes the value is a string either like "data" or some number as a string

So if the file I are creating 3 times is called "data", I want to convert it into:

data_0
data_1
data_2

Also if the value is the a number (but it string format) such as 145 I want to change that to:

145
146
147 

Currently my code produces something like this:

data_0, 
data_0_1, 
data_0_1_2

or

145_0, 
145_0_1, 
145_0_1_2

Below is my code:

for index in range(0,len(test)):
      test[index]["value"]= test[index]["value"] + str(number)

I am using str(number) because otherwise I get this error:

TypeError: coercing to Unicode: need string or buffer, int found

JSON file example:

"test": [{
    "type": "text",
    "value": "data"
}, {
    "type": "integer",
    "value": "145"
}]

Any advice would be appreciated.

Catherine
  • 727
  • 2
  • 11
  • 30
  • 1
    add the content of `test` please. – Avión Mar 21 '16 at 14:13
  • @Borja I have added the content of test – Catherine Mar 21 '16 at 14:16
  • @Borja It is a json file that I import and read in python, which is working correctly for me. That is the json format. – Catherine Mar 21 '16 at 14:20
  • 1
    It's the first time you mention the word `json` in your post. Please, always be very specific. – Avión Mar 21 '16 at 14:21
  • Can you please clarify the question? What is wrong with your code? How would you like to improve it? – Yaron Mar 21 '16 at 14:26
  • @Yaron My code produces data_0, data_0_1, data_0_1_2 or 145_0, 145_0_1,145_0_1_2 instead of producing data_0, data_1, data_2 or 145, 146, 147 – Catherine Mar 21 '16 at 14:35
  • At his time, your code produces `data0`, `data1`, if you want to get `data_0`, `data_1` you should use `test[index]["value"]= test[index]["value"] + "_" + str(number)` – Avión Mar 21 '16 at 14:36

2 Answers2

1

You can use a try & catch to check if the input is an integer or a string. If it's an int you sum 1 to the number, if it's a string you just append the _index.

test = [{"type": "text", "value": "data"}, {"type": "integer","value": "145"}]

for index in range(0,len(test)):
    try:
        # Test if the value is an integer
        test[index]["value"]= int(test[index]["value"]) + index

    except ValueError:
        # The value is an string
        test[index]["value"]= test[index]["value"] + "_" + str(index)

print test

Outputs:

[{'type': 'text', 'value': 'data_0'}, {'type': 'integer', 'value': 146}]
Avión
  • 7,963
  • 11
  • 64
  • 105
0

Borja's answer is good and follows the EAFP principle. Your code can be cleaned up a little if you use enumerate and str.format.

for index, dictionary in enumerate(test):
    try:
        dictionary['value'] = int(dictionary['value']) + 1

    except ValueError:
        dictionary['value'] += '_{}'.format(index)
Community
  • 1
  • 1
Jared Goguen
  • 8,772
  • 2
  • 18
  • 36