Page 1 of 1

JSON data parsing

Posted: 21 Jan 2014 01:54
by srjohn
Hi,
I have a JSON response something like below"
[{"ud":true,"range":"","time":"2014\/01\/21","value":"","no":"0","key1":0},{"ud":true,"range":"114","time":"09:46:00","value":"5,050","no":"155","key1":155},{"no":"200","v2":333,"value":"33,383,841,250","range":"","time":"09:46:00","ud":true,"key1":200},{"ud":true,"range":"283,157","time":"09:46:00","value":"1,802,052","no":"201","key1":201}]
I only want to get the value for key1==200.
For this example, I only want to get "33,383,841,250" string.
Is there anyone can help me out how to parse the string out?

Thanks and Best Regards,
-srjohn

Re: JSON data parsing

Posted: 22 Jan 2014 20:36
by Martin
Hi,

You could use the functions indexOf, lastIndexOf and substring to extract the value.

Assume the JSON response is stored in a variable with name value:

Code: Select all

//the string is enclosed in single quotes so that double quotes don't need to be escaped
key_start_index = indexOf(value, '"key1":200');

//searches backwards starting from key_start_index
value_start_index = lastIndexOf(value, '"value":"', key_start_index);

//add 9 characters (length of "value":") so that we get the position where the real value starts
value_start_index = value_start_index + 9;

//search the end index of the value
value_end_index = indexOf(value, '",', value_start_index);

//extract the text
extracted_text = substring(value, value_start_index, value_end_index);
It's not very beautiful and probably needs some additional checks when the JSON does not contain key1=200 or when the value is missing.

Regards,
Martin

Re: JSON data parsing

Posted: 23 Jan 2014 01:36
by srjohn
Martin wrote:Hi,

You could use the functions indexOf, lastIndexOf and substring to extract the value.

Assume the JSON response is stored in a variable with name value:

Code: Select all

//the string is enclosed in single quotes so that double quotes don't need to be escaped
key_start_index = indexOf(value, '"key1":200');

//searches backwards starting from key_start_index
value_start_index = lastIndexOf(value, '"value":"', key_start_index);

//add 9 characters (length of "value":") so that we get the position where the real value starts
value_start_index = value_start_index + 9;

//search the end index of the value
value_end_index = indexOf(value, '",', value_start_index);

//extract the text
extracted_text = substring(value, value_start_index, value_end_index);
It's not very beautiful and probably needs some additional checks when the JSON does not contain key1=200 or when the value is missing.

Regards,
Martin
Hi Martin,
Thanks for your code!
Your logic should work, thanks!
-srjohn