0

I get the following json data from server.

{"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]}

and i need to convert it to following format:

{"1":"82700","2":"26480","3":"31530","4":"22820","5":"15550","6":"205790"}

I have the following code but not working out:

       var cities = "{";

        for (var key in data.visits) {
            var val = data.visits[key];
            //Now you have your key and value which you 
            //can add to a collection that your plugin uses
            var obj = {};
            obj[val.City] = '' + val.Count;

            var code = '' + val.City;
            var count = '' + val.Count;

            cities += code + ':' + count + ',';
        }

        cities += "}";

I need the integers in string representation and need to get rid of the final , .

How can i fix this?

0

2 Answers 2

1

Try this

var data    = {"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]};
var result = {};

for (var i = 0; i < data.visits.length; i++) {
  result[data.visits[i].City] = String(data.visits[i].Count);
}

Example

Keys in object always converts to string you don't need convert it to string manually. If you need convert all object to JSON string you can use JSON.stringify(result);

Sign up to request clarification or add additional context in comments.

Comments

1

How I understood you want to create new json with given json.you can parse it,run with cycle on it,and create a new json whatever kind of you want. here is a link which can help you. http://www.w3docs.com/learn-javascript/working-with-json.html

Comments

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.